C - Nested if Statements

Introduction

It's possible to have ifs within ifs. These are called nested ifs.

For example:

In programming terms, this corresponds to the following:

if(expression1)                             
{
  StatementA;                               
  if(expression2)                           
    StatementB;                             
  else
    StatementC;                             
}
else
  StatementD;                               
Statement E;                                

The following code uses nested ifs to analyze numbers.

Demo

#include <stdio.h>
#include <limits.h>               // For LONG_MAX

int main(void)
{
      long test = 0L;                 // Stores the integer to be checked

      printf("Enter an integer less than %ld:", LONG_MAX);
      scanf(" %ld", &test);

      // Test for odd or even by checking the remainder after dividing by 2
      if(test % 2L == 0L)
      {//from   w  ww  .  j a  v a2s  .c  om
        printf("The number %ld is even", test);

        // Now check whether half the number is also even
        if((test/2L) % 2L == 0L)
        {
          printf("\nHalf of %ld is also even", test);
          printf("\nThat's interesting isn't it?\n");
        }
      }
      else
        printf("The number %ld is odd\n", test);
      return 0;
}

Result

how It Works

The prompt for input uses the LONG_MAX symbol defined by a macro in the limits.h header file.

This value specifies the maximum value of type long.

The first if condition tests for an even number:

if(test % 2L == 0L)

When the expression is true, the block that follows will be executed:

{
      printf("The number %ld is even", test);

      // Now check whether half the number is also even
      if((test/2L) % 2L == 0L)
      {
        printf("\nHalf of %ld is also even", test);
        printf("\nThat's interesting isn't it?\n");
      }
}

Related Topic