Introduction to Conditional Statements
Conditional statements allow programs to make decisions and execute different blocks of code based on certain conditions. They are fundamental to creating dynamic and responsive programs.
💡 Key Concept
Conditional statements evaluate expressions that return true (non-zero) or false (zero). Based on this evaluation, different code paths are executed.
1. The If Statement
Syntax
if (condition) {
// Code to execute if condition is true
statement1;
statement2;
// ... more statements
}
Detailed Explanation
The if statement is the simplest form of conditional execution. It evaluates a condition, and if the condition is true (non-zero), the code block within the curly braces is executed.
Key Points:
- Condition: Any expression that evaluates to true (non-zero) or false (zero)
- Execution: Code block executes only if condition is true
- Single Statement: If only one statement follows, curly braces are optional (but recommended for clarity)
Example 1: Basic If Statement
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18) {
printf("You are an adult.\n");
printf("You can vote.\n");
}
printf("Program continues...\n");
return 0;
}
Output:
You are an adult.
You can vote.
Program
continues...
Example 2: If without Braces (Single Statement)
#include <stdio.h>
int main() {
int number = 10;
// Single statement - braces optional
if (number > 0)
printf("Positive number\n");
return 0;
}
Flowchart Representation
2. The If-Else Statement
Syntax
if (condition) {
// Code to execute if condition is true
statement1;
} else {
// Code to execute if condition is false
statement2;
}
Detailed Explanation
The if-else statement provides two alternative paths: one executes when the condition is true, and the other executes when the condition is false.
Key Points:
- Mutually Exclusive: Only one block (if or else) will execute
- Complete Coverage: Handles both true and false cases
- Else Block: Executes when if condition is false
Example 1: Even-Odd Checker
#include <stdio.h>
int main() {
int number = 7;
if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
return 0;
}
Output: The number is odd.
Example 2: Voting Eligibility with Detailed Messages
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are eligible to vote.\n");
printf("Please register if you haven't
already.\n");
} else {
int years_left = 18 - age;
printf("You are not eligible to vote
yet.\n");
printf("Come back in %d years.\n",
years_left);
}
return 0;
}
Flowchart Representation
3. The If-Else Ladder
Syntax
if (condition1) {
// Code for condition1 true
} else if (condition2) {
// Code for condition2 true
} else if (condition3) {
// Code for condition3 true
} else {
// Code if all conditions are false
}
Detailed Explanation
The if-else ladder allows testing multiple conditions sequentially. It checks conditions from top to bottom and executes the block corresponding to the first true condition.
Key Points:
- Sequential Checking: Conditions are checked in order
- First Match Wins: Only the first true condition's block executes
- Efficient: Stops checking once a true condition is found
- Default Case: Else block handles cases where no condition matches
Example 1: Grade Calculator
#include <stdio.h>
int main() {
int marks = 75;
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else if (marks >= 50) {
printf("Grade: C\n");
} else {
printf("Grade: F (Fail)\n");
}
return 0;
}
Output: Grade: B
Example 2: Temperature Category
#include <stdio.h>
int main() {
float temperature;
printf("Enter temperature in Celsius: ");
scanf("%f", &temperature);
if (temperature > 35) {
printf("Hot weather\n");
} else if (temperature > 25) {
printf("Pleasant weather\n");
} else if (temperature > 15) {
printf("Cool weather\n");
} else if (temperature > 0) {
printf("Cold weather\n");
} else {
printf("Freezing weather\n");
}
return 0;
}
Flowchart Representation
4. The Switch Statement
Syntax
switch (expression) {
case constant1:
// Code for constant1
break;
case constant2:
// Code for constant2
break;
// ... more cases
default:
// Code if no case matches
break;
}
Detailed Explanation
The switch statement provides an efficient way to dispatch execution to different parts of code based on the value of an expression. It's ideal when you have multiple choices for a single variable.
Key Points:
- Expression: Must evaluate to an integer or character
- Case Labels: Must be constant expressions (no variables)
- Break Statement: Prevents "fall-through" to next case
- Default Case: Optional, executes when no case matches
- Efficiency: Faster than multiple if-else statements for many conditions
Example 1: Day of Week
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid day
number\n");
}
return 0;
}
Output: Wednesday
Example 2: Calculator with Switch
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 /
num2;
} else {
printf("Error:
Division by zero!\n");
return 1;
}
break;
default:
printf("Error: Invalid
operator!\n");
return 1;
}
printf("Result: %.2lf %c %.2lf = %.2lf\n", num1,
operator, num2, result);
return 0;
}
Important: The Break Statement
⚠️ Warning: Forgetting Break
If you forget the break
statement, execution will "fall
through" to the next case, which is usually not desired!
// INCORRECT: Missing break statements
switch (day) {
case 1: printf("Monday");
case 2: printf("Tuesday"); // Will also print if
day==1!
case 3: printf("Wednesday"); // Will also print if
day==1 or 2!
}
When to Use Which Conditional Statement?
Statement | Best Use Case | Advantages | Limitations |
---|---|---|---|
if | Single condition check | Simple, straightforward | Only handles true case |
if-else | Two mutually exclusive paths | Handles both true and false cases | Only two choices |
if-else ladder | Multiple conditions to check in order | Flexible, can handle ranges | Can be inefficient with many conditions |
switch | Single variable with multiple constant values | Fast, clean, readable for many choices | Only works with integers/chars, constant cases |
Practice Exercises
Exercise 1: Leap Year Checker
Problem: Write a program that checks if a year is a leap year.
Rules: A year is a leap year if:- It is divisible by 4, but not by 100, OR
- It is divisible by 400
Exercise 2: Simple Menu System
Problem: Create a menu system that allows users to:
- 1. Check if number is positive/negative
- 2. Check if number is even/odd
- 3. Exit the program
Use switch statement for menu selection.
Exercise 3: Triangle Type Identifier
Problem: Given three sides of a triangle, determine if it is:
- Equilateral (all sides equal)
- Isosceles (two sides equal)
- Scalene (no sides equal)
- Not a triangle (sum of any two sides ≤ third side)
Summary
✅ If Statement
Use for single condition checks. Executes code only when condition is true.
✅ If-Else Statement
Use when you need two mutually exclusive paths. Handles both true and false cases.
✅ If-Else Ladder
Use for multiple conditions that need to be checked in sequence. First true condition wins.
✅ Switch Statement
Use when comparing a single variable against multiple constant values. Fast and clean.
💡 Best Practice Tip
Always use curly braces {}
with if statements, even for
single statements. This prevents errors when adding more statements
later and makes code more readable.