Wednesday, September 2, 2009

using tips If-Else statement in C programming

  1. if the expression is evaluated with true then it is replace with 1 otherwise  replaced with 0.

Example : if( 5>3)
                 Printf(“YES”);
                        Else
                 Printf(“no”);
  1. if multiple statement are given in the if expression the order of evaluation is form left to right.

Example  int a=5;
                If (a++ ,a=a-5,a--;a)
                  Printf(“yes”);
                Else
                        Printf(“NO”);
3.Nested if can be replace with logical && operator
   Example :-
       Int a=1,b=2,c=3;
      If(a==1)
   If(b==2)
If(c==3)
 Printf(“BOSS”);

  1. ternary operator (?:) sometimes replaced the if statement .

example : if (a>65)
  printf(“hi”;
else
 printf(“bye”);

using ternary operator:
a>65?printf(“hi”);printf(“bye”);
  1. hanging if is not allowed , and it always cause an error misplaced else

       example:
   if(6>2)
printf(“yes”);
printf(“no”);
else

printf(“bye”);

  1. ‘else ‘ is optional part of the if statement

  1. else(:) is compulsory in conditional operator .

example :
 64>3 ? printf(“yes”) : printf(“”);

  1. nested if is differ from multiple if

example :
nested if

int a=1,b=2,c=3;
if(a==1)
if(b==2)
if(c==3)
printf(“BOSS”);

multiple if
int avg=75;
if(( avg>=60)
printf(“first”);
if (avg>=40 && avg<60)

   printf(“second”);
if(avg>=30 && avg<40)


  1. There are other conditional statement like #if , #else , #elseif etc used with preprocessor directive
  2. alwaysuse the “else  if” instead of multiple if.

Int avg=75;
If(avg>=60)
 Printf(“first”);
If(avg>=40 && avg<60)

 Printf(“second”);
If (avg>= 30 && avg<40)>


Use else if

Int avg=75;
If(avg>=60)
 Printf(“first”);
Else If(avg>=40 )
 Printf(“second”);
Else (avg>= 30 )
…………..


            

No comments:

Blog List