Friday, July 29, 2016

C Basics - Nested if-else Statement in C

It is allowed to write an if-else construct within either the body of the if statement or the body of an else statement. This is called ‘nesting’of ifs.

The syntax for a nested if statement is,

if( boolean_expression 1) {

   /* Executes when the boolean expression 1 is true */
   if(boolean_expression 2) {
      /* Executes when the boolean expression 2 is true */
   } else {
   /* statement(s) will execute if the boolean expression 2 is false */
   }
} else {
   /* statement(s) will execute if the boolean expression 1 is false */
}

You can nest else if...else in the similar way as you have nested if statements.

/* Demonstration of nested if-else statement */ 
#include <stdio.h>
int main( ) 
{ 
 int num ; 
 printf ( "\nEnter a number less than 10: " ) ; 
 scanf ( "%d", &num ) ; 

 if ( num < 10 ) 
 {
  printf ( "\nThanks! I got your number %d", num) ; 
  if ( num ) 
   printf ( "\n The number %d is non-zero", num) ;
  else 
   printf ( "\n The number is zero" ) ;
 }else{
  printf ( "\n The number %d is not less than 10", num ) ;
  if ( num ) 
   printf ( "\n The number %d is non-zero", num) ;
  else 
   printf ( "\n The number is zero" ) ;
 }
}

Output of above program,

Enter a number less than 10: 2

Thanks! I got your number 2
 The number 2 is non-zero



Related topics:
Overview of Statements in C   |   Decision Making Statements in C   |   The if Statement in C   |   The if-else Statement in C   |   The else-if Statement in C   |   Forms of if Statement in C   |   Switch Statement in C   |   Conditional Operator Statement in C   |   The null Statement in C

List of topics: C Programming

No comments:

Post a Comment