If-else statements
If-else Statements An if-else statement is a conditional statement used in C programming to execute different code based on a specific condition. It...
If-else Statements An if-else statement is a conditional statement used in C programming to execute different code based on a specific condition. It...
An if-else statement is a conditional statement used in C programming to execute different code based on a specific condition. It has two parts:
1. Condition:
An if statement checks if a condition is true or false.
The condition can be a simple expression, a variable, or a combination of both.
Example:
c
#include <stdio.h>
int main() {
int age;
// Check the user's age
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}
2. Code block:
If the condition is true, the code inside the else block is executed.
This can include printing messages, changing variables, performing calculations, or any other operation.
Example:
c
#include <stdio.h>
int main() {
int age;
// Check the user's age
age = 25;
// If age is 25, print "Eligible to vote"
if (age == 25) {
printf("You are eligible to vote.\n");
} else {
printf("You are not eligible to vote.\n");
}
return 0;
}
Benefits of using If-else:
Improves code readability by separating the condition from the code block.
Provides explicit control over which code is executed.
Makes the code more maintainable and easier to understand.
Remember:
The else block can have multiple code blocks.
The else block must follow the if statement.
The else block can have a different set of conditions and code blocks