Code Scrappers

Nested if-else Statements

An entire if-else block can be written inside either the body of the if statement or the body of an else statement. This is called ‘nesting’ of ifs.

Syntax :

if (a > 0)

	{

			if (b > c)

			p = b;

	}

else

	p = c;

NOTE 1: The second if construct is nested in the first if statement. If the condition in the first if statement is true, then the condition in the second if statement is checked. If it is false, then the else statement is executed.

C Programs using Nested if-else statements

1. Write a program to check for the relation between 2 numbers

#include<stdio.h>

void main()

{

int a=20,b=10;

if ((a >0 ) && (b>0))

{

	printf("The numbers are positive\n");

	if (a>b)

 {
			printf("a is greater than b\n");

 }

 else

 {
			printf("a is less than b\n");

 }

}

else

{
	printf("The numbers are negative\n");

}

}

Output: The numbers are positive
a is greater than b

else-if Statements

The expressions are evaluated in sequence; if an expression is true, the statement associated with it is executed, and this terminates the whole chain.

Syntax :

If (expression)

	statement...

else if (expression)

	statement...

else if (expression)

	statement...

else if (expression)

	statement...

else

	statement... 

NOTE 1: The last else part handles the "none of the above" or default case where none of the other conditions is satisfied.

C Programs using else-if statements

1. Write a program to check for the relationship between two numbers using else-if statements


#include<stdio.h>

void main()

{

int a=20,b=10;

if (a>b)

{

	printf("a is greater than b\n");

}

else if(a<b)

{

	printf("a is less than b");
}

else

{

	printf("a is equal to b");
}

}

Output: a is greater than b

<< Back Next >>