Understanding the If Statement in C – For Absolute Beginners
Imagine you're teaching a robot how to make decisions. For example:
- "If it's raining, take an umbrella."
- "If you're hungry, eat a snack."
This is exactly how the if
statement works in C programming. It helps your program make decisions based on conditions.
How Does the If Statement Work?
The if
statement checks whether a condition is true or false. If true, it runs a block of code. If false, it skips it.
Basic Syntax:
if (condition) {
// Code to run if the condition is true
}
Real-Life Example: Checking Exam Results
Let's say you wrote an exam, and the passing mark is 40. Your program should congratulate you only if your score is above 40.
Program:
#include <stdio.h>
int main() {
int your_score = 75; // Your exam score
int passing_mark = 40; // Minimum marks needed to pass
printf("Checking your result...\n");
if (your_score >= passing_mark) {
printf("Congratulations! You passed!\n");
printf("Your score: %d/100\n", your_score);
}
printf("Result check complete.\n");
return 0;
}
What Happens?
- The program checks if
your_score
(75) is greater than or equal to passing_mark
(40).
- Since 75 >= 40 is true, it runs the code inside
{ }
and prints:
Congratulations! You passed!
Your score: 75/100
- Finally, it prints
"Result check complete."
because this line is outside the if
block.
What If the Condition is False?
If your score was 30 instead of 75:
int your_score = 30; // You failed
Output:
Checking your result...
Result check complete.
The if
block is skipped because 30 >= 40
is false.
Common Mistakes to Avoid
❌ Using =
Instead of ==
=
is for assignment (giving a value).
==
is for comparison (checking if equal).
Wrong:
if (score = 50) { } // This sets score to 50, not a comparison!
Correct:
if (score == 50) { } // Checks if score is 50
❌ Forgetting Braces { }
If you skip braces, only the next line is part of the if
statement.
Wrong:
if (score > 40)
printf("Passed!\n"); // Only this runs conditionally
printf("Great job!\n"); // This ALWAYS runs (not part of if)
Correct:
if (score > 40) {
printf("Passed!\n");
printf("Great job!\n"); // Both run only if true
}
❌ Adding a Semicolon After if
if (score > 40); {
printf("This always runs!");
}
The semicolon (;
) ends the if
statement, making the { }
block run always.
When Do We Use If Statements?
- Checking passwords (if password is correct, allow login).
- Gaming logic (if player health <= 0, game over).
- Temperature control (if temp > 30°C, turn on AC).
Try This Yourself!
Modify the exam program to also check for distinction (score >= 80).
Hint:
if (your_score >= 80) {
printf("Wow! You got a distinction!\n");
}
Summary
- ✅
if
helps make decisions in code.
- ✅ It runs code only if the condition is true.
- ✅ Avoid common mistakes like
=
vs ==
and missing braces.
- ✅ Used in games, apps, and real-world devices.
Now, try writing your own if
statement!