Index
What you will Learn
In this tutorial, you will learn about the if and else statement in C programming with the help of examples.
Syntax
The syntax of if else statement in C Programming looks like
if(statement){
// Run this code if the statement is true
}
else{
// Run this code if the statement is false
}
Lets see the example:-
// Check whether someone is eligible for voting or not
#include <stdio.h>
int main() {
int age;
printf("Enter your Age: ");
scanf("%d", &age);
// If your age is or greater than 18, you eligible for voting
if (age >= 18) {
printf("since your age is %d, you are eligible for voting", age);
}
else {
printf("Oops sorry! your age is %d less than the require age", 18-age);
}
return 0;
}
C if & else Ladder
The if & else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The if & else ladder allows you to check between multiple test expressions and execute different statements.
Syntax of if & else Ladder
if (statement) {
// code to execute
}
else if(statement) {
// code to execute
}
else if (statement) {
// code to execute
}
.
.
else {
// code to execute
}
Example : if & else Ladder
// school grading according to marks got by any student
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks out of 100 ");
scanf("%d", &marks);
//check if the marks between 0 and 33
if(marks >= 0 && marks < 33) {
printf("You got grade 'D', Don't worry Work hard");
}
//check if the marks between33 and 50
else if (marks >=33 && marks < 50) {
printf("You got grade 'C', Work Hard");
}
//check if the marks between 50 and 75
else if (marks >=50 && marks < 75) {
printf("You got grade 'B', Need to Improve");
}
//check if the marks between 75 and 100
else if (marks >=75 && marks <= 100) {
printf("You got grade 'A', Excellent Performance");
}
else {
printf("You Have entered incorrect number");
}
return 0;
}
Nested if & else
In some situation we need to add if & else inside the body of another if & else statement