Computersnyou

C Programming – Conditional Statements

Posted on  3/7/2012

 

In any programming language condition checking is very important.Many languages support this feature and C is one of them.

We can check a condition whether it is ‘true’ or ‘false’ by using ‘if-else clause’ or by using ‘if-elseif-else clauses

We can also use nested ‘if-else’ clause or ‘if-elseif-else’ clause i.e. within a ‘if-else’ clause or ‘if-elseif-else’ clause we can use as many clause as we like.

Illustration with Example

# include<stdio.h></stdio.h>

int main()

{

int a=1,b=2,c=3;

if(a

{

         if(c

         {

                 printf(“nnB is the Greatest Number Among All Three Numbersnn”);

         } 

               else

               {

                       printf(“nnC is the Greatest Number Among All Three Numbersnn”);

               }

         }

else

{

      if(c

{

               printf(“nnA is the Greatest Number Among All Three Numbersnn”);

}

             else

            {

                       printf(“nnC is the Greatest Number Among All Three Numbersnn”);

             }

      }

return 0;

}

Output

C is the Greatest Number Among All Three Numbers

 

Explanation

First of all I initialized the variables a,b, and c of int type with the value 1,2, and 3 respectively.

Then the condition in the if clause is checked which returns true so the program controller get inside the if part.

Inside the if part we again have an ‘if-else’ clause.

Again the if condition is checked first which returns false so the program controller get insde the else part

And inside the else part I used a printf function to output a message on the Console or Screen

“C is the Greatest Number Among All Three Numbers”

Since, the if part of the ‘if-else’ clause first appears to be true so the else part will not be executed.

 

Tips

If there are many ‘if-elseif-else’ clauses then just remember one thing, the part which first evaluates to be true will only be executed and rest of the clauses will be ignored.

 

If you have any query then do leave us a comment.


  • Home
  • About