Welcome to the exciting world of C programming! Today, we'll learn about one of the most fundamental concepts: the else-if ladder.
else-if Ladder?An else-if ladder, also known as a multiple conditional statements, is a series of if-else statements that are linked together. Each if statement checks a condition, and if the condition is true, the corresponding code block is executed. If the condition is false, the program moves on to the next else-if statement.
if (condition1) {
// Code block for condition1
} else if (condition2) {
// Code block for condition2
} else if (condition3) {
// Code block for condition3
} else {
// Default code block
}š” Pro Tip: The conditions are checked from top to bottom. If a condition is true, the program stops checking the remaining conditions and executes the corresponding code block.
Let's consider a practical example. We'll create a program that checks the grade of a student based on their marks.
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
if (marks >= 90 && marks <= 100) {
printf("A+ Grade\n");
} else if (marks >= 80 && marks < 90) {
printf("A Grade\n");
} else if (marks >= 70 && marks < 80) {
printf("B Grade\n");
} else if (marks >= 60 && marks < 70) {
printf("C Grade\n");
} else if (marks >= 50 && marks < 60) {
printf("D Grade\n");
} else {
printf("Fail\n");
}
return 0;
}In this example, we're asking the user to enter their marks. Then, we're checking each condition one by one. If the user's marks are greater than or equal to 90 and less than or equal to 100, we print "A+ Grade". If not, we check the next condition, and so on.
What is an `else-if` ladder in C programming?
In the next lesson, we'll dive deeper into C programming and explore more exciting topics together! šÆ