Pages

Wednesday, 9 May 2018

Nested if else in C


Nested if else in C


Here you will learn about nested if else in C

In the previous tutorial we have learnt about if-else statements. Those statements provide the flexibility to check for two possible faces of answer. But it is also possible that there will be more than two options for the answer. To make things more precise, take an example of school grading system. Suppose if you want to create a program that will print the grade of student based on his/her percentage marks. Then in that case you will need at least 4 conditions to check.So to put those things on work we have to use nested if-else statements.

Nested if else in C
As the name suggests, nesting means writing if-else statements inside another if or else block. Basically there is no limit of nesting. But generally programmers nest up to 3 blocks only.

General form of nested if-else statements is given below.
if (condition)
{
    Statement 1
    Statement 2 and so on
}
else
{
    if (condition)
    {
        Statement a
        Statement b
    }
    else
    {
        Statement c
        Statement d
    }
}
It’s a bit complex structure for beginners so lets try to understand its general form.

As you can see, I have nested another if-else block inside one else block. So while executing in this form. The compiler first check the condition if (primary or first) block. If it fails then it will move on to the else block. In the else block it will check the condition of secondary if statement, if it also fails then it will execute the statements under else block.

In our general form I have nested if-else block in else block. You can also nest that if-else statement under first if statement. This will also work.

Now lets try implement our knowledge in one program.

Question: Take one number from the user. Check it whether it is negative, zero or positive and print the message for it.


#include <stdio.h>

void main()
{
 int num;
 printf("Enter any number:");
 scanf("%d",&num);

 if (num < 0)
  printf("number is negative");

 else
 {
  if (num==0)
   printf("number is 0");
  else
   printf("number is positive");
 }

#include <stdio.h>

void main()
{
 int num;
 printf("Enter any number:");
 scanf("%d",&num);

 if (num < 0)
  printf("number is negative");

 else
 {
  if (num==0)
   printf("number is 0");
  else
   printf("number is positive");
 }
}