Tutorial 5.3: Nested if Selection Structure

Nested if Statement
It is possible to have if within if statement. The if within an if is called nested if. The flowchart illustrates the concept of nested if. Do take note that if can also be place within else statement.



Lets look at an example of nested if.
#include <stdio.h>

int main()
{
 int num;
 printf("Enter a number between -10 and 10: ");
 scanf("%d", &num);
 if (num > 0) {
  printf("%d is a positive number\n", num);
  if (num %2 == 0)
   printf("%d is an even number\n", num);
  else
   printf("%d is an odd number\n", num);
 } 
 else
  printf("%d is a negative number\n", num);
 return 0;
}
Sample output:

Enter a number between -10 and 10: 6
6 is a positive number
6 is an even number

Explanation:
if (num > 0) {
 printf("%d is a positive number\n", num);
 if (num %2 == 0)
  printf("%d is an even number\n", num);
 else
  printf("%d is an odd number\n", num);
} 
else
 printf("%d is a negative number\n", num);
Here we have if else selection structure within the if statement that tests whether the variable num is an even or odd number. Notice that the nested if will only be checked if the condition of the if statement is true. The braces enclosing the nested if are necessary to make the nested if a part of if (first) statement.

Next: switch Statement

5 comments:

The Everyting In My Life said...

thanks

Clay said...

Replace "choice" with "num" or vice versa.

Unknown said...

right

Evan said...

Programming made easier with flowchart, interesting. I found more about this tipic @ creately

Unknown said...

Flow chart is foundation to analyze and solve the problem in easy way.

Post a Comment