Docs
Control Flow
if, else, and else if Statements
π Introduction
Decision-making is fundamental to programming. The if, else, and else if statements allow your program to make choices based on conditions, executing different code paths depending on whether conditions are true or false.
π― Flow of Decision Making
βββββββββββββββ
β Start β
ββββββββ¬βββββββ
β
βΌ
βββββββββββββββββββ
β Is condition β
β true? β
ββββββββββ¬βββββββββ
β
βββββββββββββββββ΄ββββββββββββββββ
β Yes β No
βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ
β Execute if β β Execute else β
β block β β block (if any) β
ββββββββββ¬βββββββββ ββββββββββ¬βββββββββ
β β
βββββββββββββββββ¬ββββββββββββββββ
β
βΌ
βββββββββββββββ
β End β
βββββββββββββββ
π The if Statement
Basic Syntax:
if (condition) {
// Code to execute if condition is true
}
Simple Example:
int age = 18;
if (age >= 18) {
printf("You are an adult.\n");
}
How It Works:
- β’The condition inside
()is evaluated - β’If the condition is true (non-zero), the code block executes
- β’If the condition is false (zero), the code block is skipped
Single Statement (No Braces):
if (x > 0)
printf("x is positive\n");
// Or on one line:
if (x > 0) printf("x is positive\n");
β οΈ Best Practice: Always use braces
{}, even for single statements, to prevent bugs when code is modified later.
π The if-else Statement
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
int number = 7;
if (number % 2 == 0) {
printf("%d is even\n", number);
} else {
printf("%d is odd\n", number);
}
Flowchart:
ββββββββββββββββββββ
β number % 2 == 0? β
ββββββββββ¬ββββββββββ
β
Yes β No
βββββββββββββ΄ββββββββββββ
βΌ βΌ
βββββββββββ βββββββββββ
β Print β β Print β
β "even" β β "odd" β
βββββββββββ βββββββββββ
π The else if Ladder
Syntax:
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else if (condition3) {
// Code if condition3 is true
} else {
// Code if all conditions are false
}
Example - Grade Calculator:
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else if (score >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}
How It Works:
- β’Conditions are evaluated top to bottom
- β’First true condition's block executes
- β’Remaining conditions are skipped
- β’
elsecatches all remaining cases
ποΈ Nested if Statements
Syntax:
if (outerCondition) {
if (innerCondition) {
// Nested block
}
}
Example:
int age = 25;
int hasLicense = 1;
if (age >= 18) {
if (hasLicense) {
printf("You can drive.\n");
} else {
printf("You need a license to drive.\n");
}
} else {
printf("You are too young to drive.\n");
}
Flowchart:
βββββββββββββββββββ
β age >= 18? β
ββββββββββ¬βββββββββ
β
Yes β No
βββββββββββββββββ΄ββββββββββββββββ
βΌ βΌ
βββββββββββββββββββ βββββββββββββββββββ
β hasLicense? β β "Too young" β
ββββββββββ¬βββββββββ βββββββββββββββββββ
β
Yes β No
ββββββββ΄βββββββ
βΌ βΌ
βββββββ ββββββββββββ
β"Can β β"Need β
βdrive"β βlicense" β
βββββββ ββββββββββββ
β‘ Conditions and Expressions
Relational Operators in Conditions:
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 5 |
!= | Not equal to | x != 0 |
< | Less than | x < 10 |
> | Greater than | x > 0 |
<= | Less than or equal | x <= 100 |
>= | Greater than or equal | x >= 1 |
Logical Operators:
| Operator | Meaning | Example |
|---|---|---|
&& | AND | x > 0 && x < 10 |
|| | OR | x < 0 || x > 100 |
! | NOT | !found |
Examples:
// AND - both conditions must be true
if (age >= 18 && hasID) {
printf("Entry allowed\n");
}
// OR - at least one condition must be true
if (isAdmin || isOwner) {
printf("Full access granted\n");
}
// NOT - inverts the condition
if (!isLoggedIn) {
printf("Please log in\n");
}
// Combined conditions
if ((age >= 18 && hasID) || isVIP) {
printf("Welcome!\n");
}
π― Truth in C
In C, conditions are evaluated as integers:
| Value | Meaning |
|---|---|
0 | False |
| Any non-zero value | True |
int x = 5;
if (x) { // True (x is non-zero)
printf("x is non-zero\n");
}
if (0) { // False
printf("This never prints\n");
}
if (-1) { // True (non-zero)
printf("-1 is considered true\n");
}
β οΈ Common Mistakes
1. Assignment vs Comparison:
// WRONG: Assignment (always true if x != 0)
if (x = 5) {
printf("This always executes!\n");
}
// CORRECT: Comparison
if (x == 5) {
printf("x equals 5\n");
}
2. Dangling else Problem:
// Ambiguous - which if does else belong to?
if (a > 0)
if (b > 0)
printf("a and b positive\n");
else
printf("Which condition is this for?\n");
// Clear with braces:
if (a > 0) {
if (b > 0) {
printf("a and b positive\n");
}
} else {
printf("a is not positive\n");
}
3. Empty Statement:
// WRONG: Semicolon after if creates empty statement
if (x > 0); // Empty statement executed
{
printf("Always executes!\n"); // Not part of if
}
// CORRECT:
if (x > 0) {
printf("x is positive\n");
}
4. Floating-Point Comparison:
float f = 0.1 + 0.2;
// WRONG: Direct comparison
if (f == 0.3) { // May fail due to precision
printf("Equal\n");
}
// CORRECT: Use tolerance
if (fabs(f - 0.3) < 0.0001) {
printf("Approximately equal\n");
}
π The Ternary Operator (Conditional Expression)
A compact form of if-else for simple assignments:
Syntax:
result = (condition) ? value_if_true : value_if_false;
Examples:
// Traditional if-else
int max;
if (a > b) {
max = a;
} else {
max = b;
}
// Using ternary operator
int max = (a > b) ? a : b;
// In printf
printf("Status: %s\n", (isActive) ? "Active" : "Inactive");
// Nested ternary (use sparingly)
char grade = (score >= 90) ? 'A' :
(score >= 80) ? 'B' :
(score >= 70) ? 'C' : 'F';
π’ Multiple Conditions Pattern
Range Checking:
// Check if value is in range [0, 100]
if (value >= 0 && value <= 100) {
printf("Value is in valid range\n");
}
// Check if character is a digit
if (ch >= '0' && ch <= '9') {
printf("Character is a digit\n");
}
// Check if character is a letter
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
printf("Character is a letter\n");
}
Validation Chain:
int validate(int age, int income, int score) {
if (age < 18) {
printf("Must be 18 or older\n");
return 0;
}
if (income < 30000) {
printf("Income too low\n");
return 0;
}
if (score < 650) {
printf("Credit score too low\n");
return 0;
}
printf("Application approved!\n");
return 1;
}
π Short-Circuit Evaluation
Logical operators evaluate left-to-right and stop early:
AND (&&):
- β’If left side is false, right side is not evaluated
// Safe: division only happens if b != 0
if (b != 0 && a / b > 2) {
printf("Ratio is greater than 2\n");
}
OR (||):
- β’If left side is true, right side is not evaluated
// If isAdmin is true, hasPermission() is not called
if (isAdmin || hasPermission()) {
grantAccess();
}
π·οΈ Best Practices
- β’Always use braces for clarity
- β’Put constants on the left in comparisons (Yoda conditions)
if (5 == x) // Compiler error if you write = instead of == - β’Keep conditions simple - extract complex logic to variables
int isValidUser = (age >= 18 && hasAccount && !isBanned); if (isValidUser) { ... } - β’Order conditions by likelihood for efficiency
- β’Avoid deep nesting - consider early returns
- β’Use meaningful variable names that read like English
β Summary
| Statement | Purpose |
|---|---|
if | Execute code when condition is true |
else | Execute code when if condition is false |
else if | Check additional conditions |
Nested if | Check conditions within conditions |
Ternary ?: | Compact if-else for expressions |
π Key Takeaways
- β’
ifevaluates a condition and executes code if true - β’
elseprovides an alternative path whenifis false - β’
else ifallows multiple condition checking - β’Use
==for comparison, not= - β’Non-zero values are true, zero is false
- β’Logical operators
&&,||,!combine conditions - β’Ternary operator offers compact conditional expressions
- β’Always use braces for code blocks
βοΈ Next Topic
Continue to switch-case statements for multi-way branching.