Wednesday

Nested if...else statement (if...elseif....else Statement)


Nested if...else statement (if...elseif....else Statement)

The if...else statement can be used in nested form when a serious decision are involved.

Syntax of nested if...else statement.

if (test expression)
     statements to be executed if test expression is true;
else
     if(test expression 1)
          statements to be executed if test expressions 1 is true;
       else
          if (test expression 2)
           .
           .
           .
            else
              statements to be executed if all test expressions are false;

How nested if...else works?

If the test expression is true, it will execute the code before else part but, if it is false, the control of the program jumps to the else part and check test expression 1 and the process continues. If all the test expression are false then, the last statement is executed.
The ANSI standard specifies that 15 levels of nesting may be continued.

Example of nested if else statement

Write a C program to relate two integers entered by user using = or > or < sign.
#include <stdio.h>
int main(){
     int numb1, numb2;
     printf("Enter two integers to check".\n);
     scanf("%d %d",&numb1,&numb2);
     if(numb1==numb2) //checking whether two integers are equal.
          printf("Result: %d=%d",numb1,numb2);
     else
        if(numb1>numb2) //checking whether numb1 is greater than numb2.
          printf("Result: %d>%d",numb1,numb2);
        else
          printf("Result: %d>%d",numb2,numb1);
return 0;
}
Output 1
Enter two integers to check.
5
3
Result: 5>3
Output 2
Enter two integers to check.
-4
-4
Result: -4=-4

Kindly Bookmark this Post using your favorite Bookmarking service:
Technorati Digg This Stumble Stumble Facebook Twitter
YOUR ADSENSE CODE GOES HERE

0 comments:

Post a Comment

Dont Forget for Commets

 

| C programing tutorials © 2009. All Rights Reserved | Template Style by My Blogger Tricks .com | Design by Brian Gardner | Back To Top |