C If...Else
Making decisions in your C programs
🤔 What are If...Else Statements?
If...else statements allow your program to make decisions by executing different code blocks based on conditions. They control the flow of your program execution.
// Simple if-else example
int age = 18;
if (age >= 18) {
printf("You can vote!");
} else {
printf("Too young to vote.");
}
Types of If Statements
Simple If
Execute code if condition is true
If-Else
Choose between two options
Else If
Multiple conditions in sequence
Nested If
If statements inside other if statements
🔹 Simple If Statement
The if statement evaluates a condition and executes its code block only when the condition is true, providing fundamental decision-making capability. The syntax if(condition) { statements; } checks whether the condition expression evaluates to non-zero (true). For example, if(temperature > 30) { printf("Hot day"); } prints the message only when temperature exceeds 30. Single statements don't require braces but using them consistently prevents errors when adding more statements later. The condition can be any expression; relational operators (>, <, ==), logical operators (&&, ||), or function calls that return integer values all work. If statements form the foundation of program logic, enabling dynamic behavior based on runtime conditions and user input.
#include
int main() {
int number = 10;
// Simple if statement
if (number > 0) {
printf("%d is a positive number\n", number);
}
// Multiple simple if statements
if (number % 2 == 0) {
printf("%d is even\n", number);
}
if (number >= 10) {
printf("%d is greater than or equal to 10\n", number);
}
// If statement with multiple conditions
if (number > 0 && number < 100) {
printf("%d is between 1 and 99\n", number);
}
return 0;
}
Output:
10 is even
10 is greater than or equal to 10
10 is between 1 and 99
🔹 If-Else Statement
The if-else statement creates a binary decision point, executing one block when the condition is true and an alternative block when false. The structure if(condition) { true_block; } else { false_block; } ensures exactly one branch executes. For example, if(age >= 18) { printf("Adult"); } else { printf("Minor"); } categorizes based on age. This construct is essential for implementing either-or logic, handling success and failure cases, and providing default behaviors. The else clause is optional but recommended when both outcomes need specific handling. If-else statements enable programs to respond appropriately to different conditions, making them crucial for input validation, error handling, state management, and implementing business logic that requires distinct actions for different scenarios.
#include
int main() {
int age = 16;
// Basic if-else
if (age >= 18) {
printf("You are an adult\n");
} else {
printf("You are a minor\n");
}
// If-else with calculations
int a = 15, b = 25;
if (a > b) {
printf("%d is greater than %d\n", a, b);
} else {
printf("%d is not greater than %d\n", a, b);
}
// If-else for even/odd check
int num = 7;
if (num % 2 == 0) {
printf("%d is even\n", num);
} else {
printf("%d is odd\n", num);
}
return 0;
}
Output:
15 is not greater than 25
7 is odd
🔹 Else If Statement
The else if construct chains multiple conditions sequentially, testing each only if previous conditions were false, enabling multi-way decision logic. The pattern if(condition1) {} else if(condition2) {} else if(condition3) {} else {} evaluates conditions in order until one is true. For example, grade classification: if(score>=90) {grade='A';} else if(score>=80) {grade='B';} else if(score>=70) {grade='C';} assigns grades based on score ranges. Only the first matching condition executes, so order matters crucially—place specific conditions before general ones. This structure is more efficient than independent if statements when conditions are mutually exclusive, and it's more readable than deeply nested if-else blocks. Else if chains are perfect for range checking, state machines, and implementing priority-based logic.
#include
int main() {
int score = 85;
// Grade calculation using else if
if (score >= 90) {
printf("Grade: A (Excellent!)\n");
} else if (score >= 80) {
printf("Grade: B (Good!)\n");
} else if (score >= 70) {
printf("Grade: C (Average)\n");
} else if (score >= 60) {
printf("Grade: D (Below Average)\n");
} else {
printf("Grade: F (Fail)\n");
}
// Temperature check
int temp = 75;
if (temp > 100) {
printf("It's extremely hot!\n");
} else if (temp > 80) {
printf("It's hot\n");
} else if (temp > 60) {
printf("It's warm\n");
} else if (temp > 40) {
printf("It's cool\n");
} else {
printf("It's cold\n");
}
return 0;
}
Output:
It's warm
🔹 Nested If Statements
Nested if statements place one if statement inside another, enabling complex decision-making based on multiple dependent conditions. While powerful for handling sophisticated logic, excessive nesting reduces readability and maintainability. For example, checking eligibility might require if(age>=18) { if(hasLicense) { if(hasInsurance) { printf("Can drive"); }}}. Best practices suggest limiting nesting depth to 2-3 levels and using logical operators (&&, ||) to combine simple conditions instead. Alternatively, early returns, guard clauses, or breaking logic into separate functions improves clarity. Deep nesting often indicates opportunities for refactoring using else-if chains, switch statements, or function decomposition that makes code more testable and maintainable while preserving the same logical behavior.
#include
int main() {
int age = 25;
int has_license = 1; // 1 = true, 0 = false
int has_car = 0;
// Nested if for driving eligibility
if (age >= 18) {
printf("You are old enough to drive\n");
if (has_license) {
printf("You have a license\n");
if (has_car) {
printf("You can drive your own car!\n");
} else {
printf("You need to get a car\n");
}
} else {
printf("You need to get a license first\n");
}
} else {
printf("You are too young to drive\n");
}
// Another nested example - number classification
int num = -15;
if (num != 0) {
if (num > 0) {
printf("%d is positive\n", num);
if (num % 2 == 0) {
printf("and it's even\n");
} else {
printf("and it's odd\n");
}
} else {
printf("%d is negative\n", num);
}
} else {
printf("Number is zero\n");
}
return 0;
}
Output:
You have a license
You need to get a car
-15 is negative
🔹 Logical Operators in If Statements
Logical operators combine multiple conditions in if statements, enabling complex Boolean expressions without nested structures. The AND operator (&&) requires all conditions to be true, OR (||) requires at least one condition true, and NOT (!) inverts a condition's truth value. For example, if(age>=18 && hasLicense) checks both conditions simultaneously, while if(isWeekend || isHoliday) succeeds if either is true. Logical operators use short-circuit evaluation: && stops at the first false condition, and || stops at the first true condition, improving efficiency and preventing errors from evaluating undefined expressions. Understanding operator precedence (NOT before AND before OR) and using parentheses for clarity are essential for writing correct complex conditions.
#include
int main() {
int age = 22;
int income = 30000;
int credit_score = 750;
// AND operator (&&) - all conditions must be true
if (age >= 18 && income >= 25000 && credit_score >= 700) {
printf("Loan approved!\n");
} else {
printf("Loan denied\n");
}
// OR operator (||) - at least one condition must be true
int day = 6; // Saturday
if (day == 6 || day == 7) { // Saturday or Sunday
printf("It's weekend!\n");
} else {
printf("It's a weekday\n");
}
// NOT operator (!) - reverse the condition
int is_raining = 0; // 0 = false
if (!is_raining) {
printf("It's not raining, let's go out!\n");
} else {
printf("It's raining, stay inside\n");
}
// Complex condition
int hour = 14; // 2 PM
if ((hour >= 9 && hour <= 17) && !is_raining) {
printf("Good time for outdoor activities\n");
}
return 0;
}
Output:
It's weekend!
It's not raining, let's go out!
Good time for outdoor activities