banner
 

if Statement


(a) The if statement

(b) The if-else statement

(c) The conditional operators

     Here when if ststement condition true then exicute code within if for example:-

 if ( this condition is true )
{
execute this statement ;
...................
}
     
this expression is true if
 x == y x is equal to y
x != y x is not equal to y
x < y x is less than y
x > y x is greater than y
x <= y x is less than or equal to y
x >= y x is greater than or equal to y

    Here a example of if statement given below:-
if ( i<j )
{
 printf("Hello");
}
    
     Here if i will be less then j then it print "Hello" else this print nothing imean no output. 

if-else Statement


     In this case we have 2 option if condition true execute some code and if condition is false then execute other code for example:-

if ( this condition is true )
{
execute this statement ;
...................
}
else
{
execute this statement ;
...................

}

if ( i<j )
{
 printf("i is less then j");
}
else
{
 printf("i is not less then j");

}
     Here if i will be less then j then it print i is less then j and if i will not be less then j then it print i not less then j.

 if ( per >= 60 )
{
  printf ( "First division" ) ;
}
else if ( per >= 50 )
{
  printf ( "Second division" ) ;
}
else if ( per >= 40 )
{
  printf ( "Third division" ) ;
}
else
{
  printf ( "fail" ) ;
}

     Here per is percentage which decide division of student with above example. Here we are checking multiple condition one by one and get the correct result, if any condition true then no need to check next else-if condition.

The Conditional Operator


     The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is,

expression 1 ? expression 2 : expression 3

y = ( x > 8 ? 2 : 5 ) ;

This statement will store 2 in y if x is greater than 8, otherwise it will store 5 in y.