Conditional Statements
Lesson 2.5: Conditional Statements (Decision Making)
Conditional statements are essential for creating programs that can make decisions and respond to different situations. In this lesson, you'll learn how to use the if, else if, and else statements in C to control the flow of your program based on various conditions.
The if Statement
The if statement allows you to execute a block of code only if a specified condition is true.
Syntax:
C
if (condition) {
// Code to execute if the condition is true
}
Example:
C
int age = 16;
if (age >= 18) {
printf("You are eligible to vote.\n");
}
The else Statement
The else statement provides an alternative block of code to execute if the if condition is false.
Syntax:
C
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Example:
C
int number = 7;
if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
The else if Statement
The else if statement allows you to check multiple conditions in sequence. You can have as many else if blocks as needed.
Syntax:
C
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true (and condition1 is false)
} else {
// Code to execute if none of the above conditions are true
}
Example:
C
int score = 85;
if (score >= 90) {
printf("Excellent!\n");
} else if (score >= 80) {
printf("Great job!\n");
} else if (score >= 60) {
printf("Good work!\n");
} else {
printf("You need to improve.\n");
}
Nested if Statements
You can place if statements inside other if or else blocks to create more complex decision structures.
C
int temperature = 25;
int humidity = 60;
if (temperature > 20) {
if (humidity < 50) {
printf("The weather is nice!\n");
} else {
printf("The weather is hot and humid.\n");
}
} else {
printf("The weather is cool.\n");
}
Important Notes
Boolean Expressions: The condition inside an if statement must be a Boolean expression, which evaluates to either true or false.
Comparison Operators: Use relational operators (==, !=, <, >, <=, >=) and logical operators (&&, ||, !) to build Boolean expressions.
Curly Braces: Curly braces {} are optional if the code block contains only one statement. However, it's good practice to always use them for clarity and to avoid errors.
Logical Operators: The && (AND) operator requires both conditions to be true, the || (OR) operator requires at least one condition to be true, and the ! (NOT) operator negates a condition.
Let me know if you need more examples or clarifications.