Friday, July 29, 2016

C Basics - The else-if Statement in C

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.

The syntax of an if...else if...else statement is,

if(boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
   /* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
   /* Executes when the boolean expression 3 is true */
}
else  {
   /* executes when the none of the above condition is true */
}


/* Demonstration of else-if statement */ 
#include <stdio.h>
int main( ) 
{ 
 int num ; 
 printf ( "\nEnter a number less than 10: " ) ; 
 scanf ( "%d", &num ) ; 
 
 if ( num == 0 ){
  printf ( "\n The number is zero" ) ;
 }else if ( num < 10 ) {
  printf ( "\nThanks! I got your number %d", num) ; 
 }else{
  printf ( "\n The number %d is not less than 10", num ) ;
 }
}
Output of above program,

Enter a number less than 10: 4
Thanks! I got your number 4



Related topics:
Overview of Statements in C   |   Decision Making Statements in C   |   The if Statement in C   |   The if-else Statement in C   |   Nested if-else 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