In C programming, conditional statements allow you to control the flow of your program based on specific conditions. They enable you to make decisions and execute different code blocks depending on whether a certain condition is true or false. Here's an overview of the most common conditional statements in C:
1. if Statement:
C
if (condition) {
// Code to be executed if the condition is true
}
Example:
C
int number = 10;
if (number > 5) {
printf("The number is greater than 5.\n");
}
2. if-else Statement:
C
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Example:
C
int age = 20;
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote yet.\n");
}
3. if-else if Ladder:
C
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else {
// Code to be executed if all conditions are false
}
Example:
C
char grade = 'B';
if (grade == 'A') {
printf("Excellent work!\n");
} else if (grade == 'B') {
printf("Good job!\n");
} else {
printf("Keep practicing!\n");
}
4. switch Statement:
C
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// ... more cases
default:
// Code to be executed if expression doesn't match any case
}
Example:
C
int month = 5;
switch (month) {
case 12:
case 1:
case 2:
printf("Winter\n");
break;
case 3:
case 4:
case 5:
printf("Spring\n");
break;
// ... more cases
default:
printf("Invalid month\n");
}
Additional Points: