if else statement in C

The if Statement:

C uses the keyword if to implement the decision control instruction. The general form of if statement looks like this:

if(this condition is true)         
      execute this ststement;

The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses.

x==yx is equal to y
x!=yx is not equal to y
x<yx is less than y
x>yx is greater than y
x<=yx is less than or equal to y
x>=yx is greater than or equal to y
/*Demonstration of if statement*/ 
#include<stdio.h> 
int main() 
{ 
     int num; 
     printf(“Enter a number less than 10”); 
     scanf(“%d”,&num); 
     if(num<10)         
           printf(“What an obedient servant you are!\n”); 
     return 0; 
}  

The if-else Statement:

 The if statement by itself will execute a single statement, or a group of statements, when the expression following if evaluates to true. It does nothing when the expression evaluates to false. Can we execute one group of statements if the expression evaluates to true and another group of statements if the expression evaluates to false? Of course! This is what is the purpose of the else statement that is demonstrated in the following example.

Example:  In a company an employee is paid as under:

If his basic salary is less than Rs. 1500, then HRA=10% of basic salary and DA=90% of basic salary. If the employee’s salary is input through the keyboard write a program to find his gross salary.

/*Calculation of gross salary*/
#include<stdio.h>
int main()
{
         float bs, gs, da, hra;
         printf(“Enteer basic salary”);
         scanf(“%f”,&bs);
         if(bs<1500)
         {
                    hra=bs*10/100;
                    da=bs*90/100;
         }
         else
         {
                    hra=500;
                    da=bs*98/100;
         }
         gs=bs+hra+da;
         printf(“gross salary=Rs.%f\n”,gs);
         return 0;
}

A few points worth noting…

a) The group of statements after the if upto and not including the else is called an ‘if block’. Similarly, the statements after the else form the ‘else block’.

b) Notice that the else is witten exactly below the if. The statements in the if block and those in the else block have been indented to the right. This formatting convention is followed throughout the book to enable you to understand the working of the program better.

c) Had there been only one statement to be executed in the if block and only one statement in the else block we could have dropped the pair of braces.

d) As with the if statement, the default scope of else is also the statement immediately after the else. To override this default scope, a pair of braces, as shown in the above example, must be used.

Leave a Comment