Nested if...else versus an if...else ladder

suggest change

Neither form is inherently slower. A compiler can generate similar tests for both, and which one does less work depends on the data. An if/else if ladder stops at the first true condition. A nested if always enters exactly one branch of each decision. The two programs below are not equivalent: the ladder uses the final else when no value is strictly smallest, while the nested version always names one variable and can treat a tie as a unique minimum. Neither call checks that scanf converted three integers.

An if()...else ladder:

#include <stdio.h>

int main(int argc, char *argv[])
{
  int a, b, c;
  printf("\nEnter Three numbers = ");
  scanf("%d%d%d", &a, &b, &c);
  if ((a < b) && (a < c))
  {
    printf("\na = %d is the smallest.", a);
  }
  else if ((b < a) && (b < c))
  {
    printf("\nb = %d is the smallest.", b);
  }
  else if ((c < a) && (c < b))
  {
    printf("\nc = %d is the smallest.", c);
  }
  else
  {
    printf("\nImprove your coding logic");
  }
  return 0;
}

Contrast that with a nested if:

#include <stdio.h>

int main(int argc, char *argv[])
{
  int a, b, c;
  printf("\nEnter Three numbers = ");
  scanf("%d%d%d", &a, &b, &c);
  if (a < b)
  {
    if (a < c)
      {
        printf("\na = %d is the smallest.", a);
      }
    else
      {
        printf("\nc = %d is the smallest.", c);
      }
  }
  else
  {
    if(b < c)
    {
      printf("\nb = %d is the smallest.", b);
    }
    else
    {
      printf("\nc = %d is the smallest.", c);
    }
  }
  return 0;  
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents