Monday, 9 September 2019

What is Nested if else statement and How Switch Statement in C Works?

Switch statement in C

There are some situations in real life, on which we have to make some decisions. On these decisions, we need to decide what we should do next. The same situation also occurs in our programming. Block of statements will execute or not based on these decisions. Decision-making statements are also known as the conditional statement in C. These statements are:

A) If statement
B) If else statement
C) Nested if else statement
D) Switch statement in C
E) Jump Statements
i) Break
ii) Continue
iii) Goto
iv) return

See Also: Operators in C

Nested If Else Statement

If our program has more than one conditions, then, we use the nested if else statement. Each condition is checked in the nested if else statement until we get the true condition.

In the nested if else, when the condition is true, then the statements associated with this condition is executed. All other conditions are skipped.

Syntax
if (condition-1)
{
statement 1;
}
elseif (condition-2)
{
statement 2;
}
..............
else if ( condition-n)
{
statement n;
}
else
{
statement;
}

Flow of Chart for Nested if else statement in C

Switch statement in C

Example 1

Write a program to compare two integer value using nested if else statement in C.


#include <stdio.h>
int main()
{
int a, b; //Declared variables
printf ("Enter values of a and b");
scanf ("%d%d", &a, &b); 
//Compare integer values are equal or not
if (a==b)
{
printf ("Integer a and b has same values");
}
//Checks a is greater than b or not
else if (a>b)
{
printf ("Value of integer a is greater than b");
}
//Checks a is less than b or not
else
{
printf ("Value of integer a is less than b");
}
return 0;
}

Output
Enter values of a and b 12 13
Value of integer a is less than b

Explanation


First, Declared variables a and b.
Enter the values of a = 12 and b= 13.
Check first if condition i.e. (a==b), means check (12 ==13) 12 is equal to 13 or not. 12 is not equal to 13. Condition fails. Statements attached to this condition is not executed. Compiler checks next condition i.e. (a>b). a is greater than b (12>13) or not. a is not greater than b. Again condition fails. So, statements associated with it not executed. Now, the last statement attached to else will print.

See Also: Structure in C

Example 2

Write a C program to find out given triangle is equilateral, scalene or isosceles.


#include <stdio.h>
int main()
{
int side1, side2, side3; //Declared variables
printf ("Enter values of three sides of a triangle");
scanf ("%d%d%d", &side1, &side2, &side3);
//If triangle is equilateral, then all sides are equal.
if ((side1==side2)&&(side2==side3))
{
printf ("Triangle is equilateral");
}
//If triangle is scalene, then no side is equal.
else if (side1!=side2 && side2 != side3 && side3!=side1)
{
printf ("Triangle is scalene");
}
else
{
printf ("Triangle is isosceles");
}
return 0;
}


Output
Enter values of three sides of a triangle 13 12 13
Triangle is isosceles

What is the Switch Statement?

The switch statement in C reduces complex conditional and branching operations. This statement is the replacement of nested if else statement. It tests or compares the variable value with multiple cases. When the value is matched with the case, then, statements associated with it will execute. Each case has a different name and number known as the identifier.

Syntax
switch (n)
{
case1:
Statement1;
Break;
case2:
Statement2;
Break;
default:
statement;
Break;
}
Statement z;

Flow Chart of Switch Statement in C


Switch statement in C

Example 1

What happened when the break statement is not used in the switch statement?


#include <stdio.h>
int main()
{
int choice;
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1:
printf ("case 1\n");
case 2:
printf ("case 2\n");
case 3:
printf ("case 3\n");
case 4:
printf ("case 4\n");
default:
printf ("default\n");
}
return 0;
}

Output
In the above program, if the choice is 1. Then all the statements are executed because there is no break statement in the program.

Switch statement in C


When the choice is 2, then the control jumps to case 2. Execute all the statements because there is no break statement.

Switch statement in C

Example 2

What happened when multiple cases have a single statement?


#include <stdio.h>
int add(int a, int b); //Declaration of add function
int main()
{
int choice; //Declared Variables
printf ("Enter choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1:
case 2:
case 3:
case 4:
add(10, 20);
break;
case 5:
printf ("What happened\n");
break;
default:
printf ("Default\n");
}
return 0;
}
int add(int a, int b)
{
int result;
result = a+b;
printf ("result = %d\n", result);
}
Output
Switch statement in C

Let's see when the choice is 2. Even then, add function will execute.

Switch statement in C

Example 3

What happened when the switch case has the same case label?


#include <stdio.h>
int main ()
{
int choice; //Declared Variables
printf ("Enter Choice");
scanf ("%d\n",&choice);
switch (choice)
{
case 1:
printf ("Case 1");
break;
case 2:
printf ("Case 2");
break;
case 2:
printf ("Case 3");
break;
default:
printf ("default");
break;
}
return 0;
}
Output
error: duplicate case value

Example 4

What happened if the case value is a floating number in the switch statement in C.


#include <stdio.h>
int main()
{
int choice; //Declared variable
switch (choice)
{
case 1:
printf ("Case 1");
break;
case 2.5:
printf ("Case 2");
break;
default:
printf ("default");
break;
}
return 0;
}
Output
error: case label does not reduce to an integer constant

Example 5

What happened when the default case is used anywhere in the body?

#include <stdio.h>
int main()
{
    int choice; //Declaration of Variable
    printf ("Enter your choice");
    scanf ("%d", &choice);
    switch (choice)
    {
    default:
        printf ("default\n");
        break;
    case 1:
        printf ("Case 1\n");
        break;
    case 2:
        printf ("Case 2\n");
        break;
    case 3:
        printf ("Case 3\n");
        break;
    case 4:
        printf ("Case 4\n");
        break;
}
return 0;
}
Output
Enter your choice 5
default

Some Points to Remember

A) The switch statement in C must have integral value. For instance,

switch(1+2+3)
switch(1*2+12/4)
switch(a+b+c)
switch(a*b+c/d)


B) Case Values should not be duplicate.

C) It is your choice to use a default statement. If you don't want to use the default statement, then the program will run without any problem.

D) The break statement is used to terminate from the sequence of the statements.

E) A break statement is an option for the programmer. If you don't want to use the break statement, then, the execution of the program will continue until the break statement occurs.

F) Nesting of the switch statement in C is allowed. But, it makes the program complex and less readable.

Nested Switch Statement in C

When we use many switch statement inside a switch statement. Then those statements are known as a nested switch statement. For instance,
#include <stdio.h>
int main()
{
    int a = 1, b = 2; //Initialization of variables
    switch (a)
    {
    case 1:
        printf ("Outer switch loop\n");
        switch(b)
        {
        case 1:
            printf ("Case 1 switch inner loop\n");
        case 2:
            printf (" Case 2 switch inner loop\n");
            break;
        }
    }
    return 0;
}


Monday, 2 September 2019

Operator Precedence in C and Operator Associativity


If two or more operator is used in an expression, then you should know about precedence and associativity of an operator. The operator precedence in C defines priority. That means which operator should apply first on the given expression. The higher precedence operator evaluates first. But the problem occurs when the operator of the same priority is available in the expression. C Standard introduced a new term to resolve this issue. It is called associativity. The associativity defines the order. In which operators of the same priority are evaluated,  from right to left or left to right.


                                                                    Source: Neso Academy


Operator precedence in C is decreased from top to bottom in below mention table.

Operator
Description of Operator
Associativity

()
Parentheses or Function call
Left to right
[]
Brackets or array subscript
Left to right
.
Dot or member selection operator
Left to right
->
Arrow operator
Left to right
++ --

Postfix increment
Postfix decrement
Left to right

++ --
Prefix increment
Prefix decrement
Right to left
+ -
Unary plus
Unary minus
Right to left
!
Not operator
Right to left
~
Bitwise complement operator
Right to left
type
Typecast
Right to left
*
Indirection or dereference operator
Right to left
&
Address of operator
Right to left
Sizeof
Determine size in bytes
Right to left
*/%
Multiplication, division and modulus
Left to right
+ -
Addition Subtraction
Left to right
<< >>
Bitwise left shift and right shift
Left to right
< <=
>>=
Relational less than or less than equal to
Relational greater than or greater than equal to
Left to right
Left to right
== !=
Relational equal to or not equal to
Left to right
&&
Bitwise AND
Left to right
^
Bitwise Exclusive OR
Left to right
|
Bitwise Inclusive OR
Left to right
&&
Logical AND
Left to right
||
Logical OR
Left to Right
?:
Ternary operator
Right to Left
=
+=          -=
*=          /=
%=        &=
^=         |=
<<=       >>=
Assignment operator
Addition/subtraction assignment
Multiplication/division assignment
Modulus /Bitwise assignment
Bitwise exclusive/inclusive OR assignment

Right to left
,
Comma Operator
Left to right


In the above mention table, the precedence of the operator is decreased from top to bottom. The operator has higher precedence at the top and lowers precedence at the bottom. Let's understand the operator precedence in C with the help of an example.


See Also: What are C Tokens?

Example 1

Evaluate 10 + 2 *3
It is clear from the operator precedence and associativity table, multiplication operator(*) has higher priority than addition operator (+). So, 2*3 evaluates first,


operator precedence in c

Now, the addition operator performs; the result will be 16.

operator precedence in c

10 + 2 * 3 is calculated as 10+(2*3), not like (10+2)*3

Example 2

Evaluate expression of 100 + 12 / 2 - 45.

See Also: Dangling Pointer in C

In this expression, the division operator (/) has a higher priority. Precedence of the addition (+) and subtraction (-) operator is low. 

operator precedence in c

In this expression, the division operator (/) has higher precedence. So, 12/2 evaluated first. Operator (addition/subtraction) precedence in C is the same. Now, the problem arises which one evaluated first? From the above table, addition and subtraction operator is of the same precedence and associates from left to the right. In this 100+12/2-45 expression, after a division operator, the addition operator will perform then subtraction operator will perform. 


operator precedence in c

Now, Subtraction (-) operator will perform,

operator precedence in c

Example 3

Evaluate expression 10+4-6/2<3+1
In this expression, the division (/) operator has higher precedence So, 6/2 is evaluated first.

operator precedence in c

The addition (+) and subtraction (-) operator have the same priority, and its associativity is from left to right. So, after division addition (+) operator will be performed and followed by subtraction (-) operator. 

operator precedence in c


operator precedence in c


According to the operator precedence in C table, less than (<) operator has lower precedence than division (/), addition (+), subtraction(-) operator. So, < operator evaluated last.

Operator Associativity

A) We use associativity when two or more operators are of the same precedence.

B) Operator precedence in C and associativity of postfix (i++) is higher than prefix (++i).

Prefix (++i) operator has higher precedence than dereference (*) operator and postfix (i++) has higher precedence than prefix (++i) and dereference (*) operator.

If ptr is a pointer then you can write *ptr++ like *(ptr++) and ++*ptr is equivalent to ++(*p). Prefix (++i) and dereference operator are right associative.

C Program 1
#include <stdio.h>
int main()
{
char array[]="Hello";
char *ptr = array;
*ptr++;
printf ("%c", *ptr);
return 0;
}

Output
e

C Program 2
#include <stdio.h>
int main()
{
char array[]="Hello";
char *ptr = array;
++*ptr;
printf ("%c", *ptr);
return 0;
}

Output
I



C) Comma has the least precedence, so used it carefully. 

#include <stdio.h>
int main()
{
int x; //Declaration of variable x
x = 1,2; //Initaialize variable (x = 1),2;
printf ("%d\n", x);
return 0;
}

Output 
1

Following program helps you to understand operator precedence in C.

#include <stdio.h>
int main()
{
  int x = 100, y = 20, w=15, z=5, result; //Initialization of Variables
  result = (x+y)*w/z;
  printf ("Value of (x+y)*w/z %d\n", result);
  result = ((x+y)*w)/z;
  printf ( ((x+y)*w)/z %d\n", result);
  result = (x+y)* (x/y);
  printf (" Value of (x+y)*(x/y) %d\n", result);
  result = x + (y*z)/w;
  printf ("Result of x+(y*z)/w %d\n", result);
  return 0;
}

Output
Value of (x+y)*w/z 360
 ((x+y)*w)/z 360
Value of (x+y)*(x/y) 600
Result of x+(y*z)/w 106

Monday, 26 August 2019

Conditional Statement in C: If Statement.....If Else Statement in C

if else statement in C

The C programming language is a procedural programming language. In which statements are executed sequentially when no condition is applied. If the condition is applied, then the sequence of execution of the statement might be changed (based on condition evaluation). Conditional statements are also known as decision making statements in C.

See Also: Operators in C

Categorization of Conditional Statement in C

Conditional statement in C is categorized as:

if else statement in C

A) If statement
B) If-else statement in C

IF Statement in C

Before understanding, if statement lets read about syntax,

See Also: C Tokens

if (Condition)
{
//Block of the statements
}

If statement is a conditional statement in C, if the condition inside the parenthesis is true, then the block of the statement will execute. True is a non-zero value, and false is a zero value. For instance,

See Also: Pointers in C

if (a>10)
{
printf ("Hello\n");
}

Flow Chart of If Statement


if else statement in C

C program which demonstrates working of if statement
#include <stdio.h>
int main()
{
int a, b; //Initialize variables a, b
printf ("Enter the value of a and b");
scanf ("%d%d", &a, &b);
printf ("Entered value of a and b is %d %d\n", a, b);
if (a<b)
//Check condition a is smaller than b or not. If this condition is true, it prints a is smaller than b otherwise prints b is greater than b.
{
printf ("a is smaller than b\n");
}
printf ("b is greater than a\n");
return 0;
}

Output
Enter the value of a and b 10 6
Entered value of a and b is 10 6
b is greater than a

If Else Statement in C

If else statement is a decision-making statement. This statement is an extension of if statement. We try to understand the if else statement using a real-life example. Suppose you want to go to Bangalore from Delhi, to reach Bangalore you have two ways either you will go through flight or by train. You cannot use both flight and train at the same time. When your passport, flight tickets, identification id appropriates then, you will get a flight, but if anyone of the things is missed, then flight may be missed. Now, what's the next option you will go by train. From this example, you can understand that if all conditions are full-filled, then the statement attached with that condition will execute otherwise other option will choose.

Similarly, for the if else statement in C, when the condition is true (non-zero value), then the block of code with if condition will execute otherwise block of code of else will execute.

Syntax
if (Condition)
{
//Block of statements
}
else
{
//Block of statements
}

Flow Chart of If Else Statement in C



if else statement in C


C Program 1

Write a program to find out the given number is odd or even (Use if else statement in C).
To find out the given number is even or odd. The number is divided by 2. After division, if the remainder is zero, then the number is even otherwise odd.

See Also: Dangling Pointer in C

Algorithm
Step1- Start the program
Step2- Enter data: num = 13
Step3- Number is divided by 2.(num%2)
If the remainder is zero, then the given number is even else number is odd.
Step4- Stop the program

Code
#include <stdio.h>
int main()
{
int num, remainder; //Declare Variable
printf ("Enter the number");
scanf ("%d", &num);
remainder = (num%2);
if(remainder ==0)
{
printf ("The number is even %d \n", num);
}
else
{
printf ("The number is odd %d \n", num);
}
return 0;
}

Output
Enter the number 6
The number is even 6

C Program 2

Write a program to find out the given year is a leap year or not (Using if else statement in C).
A year is considered a leap year when it is divided by 4. When the remainder (year%4) is zero, it is a leap year; otherwise, it is not a leap year. For instance,
Year = 1990
Remainder = 1990%4
Remainder = 2
1990 is not a leap year

See Also: Structure in C

Algorithm
Step1- Start the program
Step2- Year = 1990
Step3- remainder = year%4 (If the remainder is equal to zero then given year is a leap year else given year is not a leap year).
Step4- Stop the program

Code
#include <stdio.h>
int main()
{
int year, remainder; //Declaration of Variable
printf ("Enter the year");
scanf ("%d", &year);
remainder = year%4;
if (remainder == 0)
{
printf ("%d is a leap year \n", year);
}
else
{
printf ("%d is not a leap year \n", year);
}
return 0;
}

Output
Enter the year 2019
2019 is not a leap year

C Program 3

Write a program to find out the given number is prime or not (Using if else statement in C)
Those number which is divided by 1 or itself are prime numbers. For instance, 2,3,5,7,19 etc.

See Also: Preprocessor directive in C

Algorithm
Step1- Start the program
Step2- Enter the number
Step3- If a number is divided by 1 and itself then given number is a prime number otherwise entered number is not a prime number.
Step4- Exit the program

Code
#include <stdio.h>
int main()
{
int num,i,count=0; //Declaration of Variables
printf ("Enter the number\n");
scanf ("%d", &num);
for (i=1;i<=num;i++)
{
if (num%i==0)
{
count++;
}
}
if(count==2)
{
printf("A Prime number is %d\n", num);
}
else
{
printf ("Not a prime number %d \n", num);
}
return 0;
}

Output
Enter the number 5
A prime number is 5

C Program 4

Write a program to find out the given number is a palindrome or not (Using if else statement in C)
A number is said to be palindrome when it is reversed it always occur the same. For instance,
number = 16361
When we reverse it, we occurred the same number. So, 16361 is a palindrome number. Suppose, if we try to reverse 163 then we get 361. So, 163 is not a palindrome number.

Algorithm
Step1- Start the program
Step2- Declare variables like a number, remainder, result, a
Step3-Initialize variable a = number
Step4- while (number!=0)
remainder = number%10
result = result * 10 + remainder
number = number/10
Step5- If enter number is equal to the output, then that number is palindrome; otherwise, it is not a palindrome number.
Step6-Stop the program

Code
#include <stdio.h>
int main()
{
int number=131, remainder, result=0,a; //Initialize variables
a=number;
while (number!=0)
{
remainder = number%10;
result=result*10+remainder;
number = number/10;
}
if (a == result)
{
printf ("%d is a palindrome number \n",a);
}
else
{
printf ("%d is not a palindrome number \n",a);
}
return 0;
}

Output
131 is a palindrome number

C Program 5

Write a program to find out the given number is Armstrong or not. (Using if else statement in C)
A number is said to be Armstrong number when the sum of cube of each digit is equal to the number itself. For instance,
Number = 123
Result = (1) ^3 +(2)^3+(3)^3
Result = 1+8+27
Result = 36
Because resultant is not equal to the number, so it is not an Armstrong number.

Algorithm
Step1- Start the program
Step2- Enter Data: num = 371
Step3-remainder = num%10
sum = sum + pow(remainder,3)
num = num/a0
Step4- When the sum of cube of each digit is equal to the entered number, then that number is Armstrong number otherwise not an Armstrong number.
Step5- Stop the program

Code
#include <stdio.h>
#include <math.h>
int main ( )
{
int num = 371, remainder, i, sum=0, a; //Initialization of variables
a=num;
while (num!=0)
{
remainder = num%10;
sum =sum+pow(remainder,3);
num=num/10;
}
if(a==sum)
{
printf ("%d is Amstrong number \n",a);
}
else
{
printf ("%d is armstrong number\n",a);
}
return 0;
}

Output
371 is an Armstrong number