Friday, July 29, 2016

C Basics - The if-else Statement in C

The purpose of if-else is to execute one group of statements if the expression evaluates to true and another group of statements if the expression evaluates to false.

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

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

If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed.

/*Demonstration of 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) ; 
 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: 4

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



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