C Language Tutorials by Ghulam Murtaza Dahar - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Output 2

Enter a number you want to check.

2

2 is even.

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;

}