C - Multiple Decisions with if else

Introduction

For the either-or type of comparisons, the if keyword has a companion - else. Together, they work like this:

if(condition) 
{ 
    statement(s); 
} 
else 
{ 
    statement(s); 
} 

When the condition is true in an if-else structure, the statements belonging to if are executed; otherwise, the statements belonging to else are executed. It's an either-or type of decision.

Demo

#include <stdio.h> 

int main() /*from www . j  av a  2s  .  c o  m*/
{ 
      int a,b; 

      a = 6; 
      b = a - 2; 

      if( a > b) 
      { 
          printf("%d is greater than %d\n",a,b); 
      } 
      else 
      { 
          printf("%d is not greater than %d\n",a,b); 
      } 
      return(0); 
}

Result

A third option

It looks like this:

if(condition) 
{ 
      statement(s); 
} 
else if(condition) 
{ 
      statement(s); 
} 
else 
{ 
      statement(s); 
} 

When the first condition proves false, the else if statement makes another test.

If that condition proves true, its statements are executed.

When neither condition is true, the statements belonging to the final else are executed.

Related Topic