What is a Nested if-else Statement?
A nested if-else the statement is simply an if-else statement placed inside another if or else block. This is typically used when you need to make a series of decisions that depend on each other.
Syntax
if (condition1) {
// Executes if condition1 is true
if (condition2) {
// Executes if condition2 is true
} else {
// Executes if condition2 is false
}
} else {
// Executes if condition1 is false
}
Example 1: Checking the Largest of Three Numbers
#include <stdio.h>
int main() {
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
if (num1 >= num2) {
if (num1 >= num3) {
printf("The largest number is: %d\n", num1);
} else {
printf("The largest number is: %d\n", num3);
}
} else {
if (num2 >= num3) {
printf("The largest number is: %d\n", num2);
} else {
printf("The largest number is: %d\n", num3);
}
}
return 0;}
Explanation:
- The program first checks if
num1 >= num2. If true, it then checks ifnum1 >= num3.
- If
num1 >= num3is also true,num1is the largest.- Otherwise,
num3is the largest.- If
num1 >= num2is false, it checks whethernum2 >= num3.
- If true,
num2is the largest.- Otherwise,
num3is the largest.
Example 2: Nested if else in c programming examples
#include <stdio.h>
int main()
{ int s;
printf ("enter your score =");
scanf("%d",&s);
if(s>=80 && s<=100){
printf("A+");
}
else if(s>=75 && s<=79){
printf("A= 3.75");
}
else if(s>=70 && s<=74){
printf("A-=3.50");
}
else if(s>=65&&s<=69){
printf("B+=3.25");
}
else if(s>=60 && s<=64){
printf("B=3.00");
}
else if(s>=55 && s<=59){
printf("B-=2.75");
}
else if(s>=50 && s<=54){
printf("c+=2.5");
}
else if(s>=45&&s<=49){
printf("c=2.25");
}
else if(s>=40&&s<=44){
printf("D=2.0");
}
else{
printf("Failed? ");
printf(" 000000 \n");
printf(" ((^^^^^^^^^^)) \n ");
printf(" (( ^^ ^^ )) \n");
printf(" (( 0 0 )) \n");
printf(" (( 00 )) \n");
printf(" (( <||||> )) \n");
printf(" ((____)) \n");
}
}
Example 3: Grading System Based on Marks
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 90) {
printf("Grade: A\n");
} else {
if (marks >= 75) {
printf("Grade: B\n");
} else {
if (marks >= 50) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
}
}
return 0;}





0 thoughts on “Nested if else in C Programming Examples || If-Else in C”