Here you’ll study nested if else in C
In the previous tutorial, we’ve learnt regarding if-else statements. Those statements offer the flexibleness to examine for 2 potential faces of the answer.
however it’s additionally potential that there’ll be over 2 choices for the solution. to create things a lot of precise, take AN example of the college grading system. Suppose if you would like to make a program which will print the grade of student supported his/her share marks.
Then therein case you’ll like a minimum of four conditions to examine.So to place those things on work we’ve to use nested if-else statements.
Nested if else in C
As the name suggests, nesting suggests that writing if-else statements within another if as an alternative block. primarily there’s no limit of nesting. however usually programmers nest up to three blocks solely.
General variety 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 small amount complicated structure for beginners, therefore, let’s attempt to perceive its general kind.
As you’ll be able to see, I even have nested another if-else block within one else block. therefore whereas capital punishment during this kind. The compiler 1st check the condition if (primary or first) block. If it fails then it’ll go to the else block. within the else block it’ll check the condition of secondary if statement, if it additionally fails then it’ll execute the statements below else block.
In our general kind I even have nested if-else block in else block. you’ll be able to additionally nest that if-else statement below 1st if statement. this may additionally work.
Now lets strive implement our information in one program.
Question: Take one range from the user. Check it whether or not it’s 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");
}
}
Output
Enter any number:- 5
Number is negative