Introduction
The if-else statement is one of the most fundamental control structures in C programming. It allows programs to make decisions and execute different blocks of code based on whether certain conditions are true or false. This decision-making capability is essential for creating programs that can respond dynamically to different situations and user inputs, making programs more intelligent and interactive.
Control structures like if-else statements give programs the ability to branch - that is, to follow different execution paths based on conditions. Without these decision-making capabilities, programs would only be able to execute instructions in a straight line, severely limiting their usefulness. The if-else statement is the foundation for building more complex decision-making logic in programming.
Key Concepts
Conditional Execution: Code blocks are executed only when specific conditions are met.
Boolean Logic: Conditions evaluate to either true (non-zero) or false (zero) in C.
Branching: The program flow can take different paths based on condition evaluation.
Nested Decisions: If-else statements can be placed inside other if-else statements for complex decision making.
Basic If Statement
Syntax
if (condition) {
// Code to execute if condition is true
}
Simple Example
#include <stdio.h>
int main() {
int age = 18;
if (age >= 18) {
printf("You are eligible to vote.\n");
}
return 0;
}
How It Works
- The condition
age >= 18is evaluated - If the condition is true (non-zero), the code inside the braces is executed
- If the condition is false (zero), the code inside the braces is skipped
- Program continues with the next statement after the if block
If-Else Statement
Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example
#include <stdio.h>
int main() {
int number = 15;
if (number % 2 == 0) {
printf("%d is an even number.\n", number);
} else {
printf("%d is an odd number.\n", number);
}
return 0;
}
Benefits of If-Else
- Guarantees that one of the two code blocks will execute
- Provides complete coverage of all possible cases (true or false)
- Makes program logic clearer and more predictable
If-Else-If Ladder
Syntax
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else if (condition3) {
// Code for condition3
} else {
// Default code if no condition is true
}
Example: Grade Calculator
#include <stdio.h>
int main() {
int marks = 85;
if (marks >= 90) {
printf("Grade: A+\n");
} else if (marks >= 80) {
printf("Grade: A\n");
} else if (marks >= 70) {
printf("Grade: B\n");
} else if (marks >= 60) {
printf("Grade: C\n");
} else if (marks >= 50) {
printf("Grade: D\n");
} else {
printf("Grade: F (Fail)\n");
}
return 0;
}
How It Works
- Conditions are evaluated from top to bottom
- The first true condition executes its corresponding code block
- All remaining conditions are skipped once a true condition is found
- If no condition is true, the final
elseblock executes (if present)
Nested If-Else Statements
Concept
If-else statements can be placed inside other if-else statements to create more complex decision structures.
Example: Login System
#include <stdio.h>
int main() {
char username[20] = "admin";
char password[20] = "password123";
char input_user[20], input_pass[20];
printf("Enter username: ");
scanf("%s", input_user);
if (strcmp(input_user, username) == 0) {
printf("Enter password: ");
scanf("%s", input_pass);
if (strcmp(input_pass, password) == 0) {
printf("Login successful! Welcome, %s!\n", username);
} else {
printf("Incorrect password. Access denied.\n");
}
} else {
printf("Username not found. Access denied.\n");
}
return 0;
}
Best Practices for Nesting
- Keep nesting levels reasonable (typically no more than 3-4 levels deep)
- Use proper indentation to show structure clearly
- Consider using logical operators to combine conditions instead of deep nesting
Conditional Operators and Expressions
Comparison Operators
int a = 10, b = 20;
if (a == b) // Equal to
if (a != b) // Not equal to
if (a < b) // Less than
if (a > b) // Greater than
if (a <= b) // Less than or equal to
if (a >= b) // Greater than or equal to
Logical Operators
int age = 25;
int hasLicense = 1; // 1 for true, 0 for false
// AND operator (&&)
if (age >= 18 && hasLicense) {
printf("Can drive legally.\n");
}
// OR operator (||)
if (age < 18 || !hasLicense) {
printf("Cannot drive legally.\n");
}
// NOT operator (!)
if (!(age >= 65)) {
printf("Not a senior citizen.\n");
}
Complex Conditions
#include <stdio.h>
int main() {
int temperature = 25;
int humidity = 60;
int isRaining = 0;
if ((temperature >= 20 && temperature <= 30) &&
(humidity < 70) && !isRaining) {
printf("Perfect weather for outdoor activities!\n");
} else {
printf("Weather conditions are not ideal.\n");
}
return 0;
}
Important Points
-
Condition Evaluation: In C, any non-zero value is considered true, and zero is considered false.
-
Braces Usage: Always use braces
{}even for single statements to avoid errors and improve readability. -
Indentation: Proper indentation makes the code structure clear and easier to understand.
-
Order Matters: In if-else-if ladders, the order of conditions is important because the first true condition stops further evaluation.
-
Complete Coverage: Use a final
elseclause to handle cases not covered by previous conditions. -
Avoid Deep Nesting: Too many nested levels make code hard to read and maintain.
Common Patterns and Examples
Pattern 1: Input Validation
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age < 0 || age > 150) {
printf("Invalid age entered.\n");
} else if (age < 13) {
printf("You are a child.\n");
} else if (age < 20) {
printf("You are a teenager.\n");
} else if (age < 60) {
printf("You are an adult.\n");
} else {
printf("You are a senior citizen.\n");
}
return 0;
}
Pattern 2: Menu Selection
#include <stdio.h>
int main() {
int choice;
printf("=== CALCULATOR MENU ===\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("Enter your choice (1-4): ");
scanf("%d", &choice);
if (choice == 1) {
printf("You selected Addition.\n");
} else if (choice == 2) {
printf("You selected Subtraction.\n");
} else if (choice == 3) {
printf("You selected Multiplication.\n");
} else if (choice == 4) {
printf("You selected Division.\n");
} else {
printf("Invalid choice. Please select 1-4.\n");
}
return 0;
}
Pattern 3: Range Checking
#include <stdio.h>
int main() {
float gpa;
printf("Enter your GPA: ");
scanf("%f", &gpa);
if (gpa < 0.0 || gpa > 4.0) {
printf("Invalid GPA. Must be between 0.0 and 4.0.\n");
} else {
if (gpa >= 3.7) {
printf("Excellent! Dean's List.\n");
} else if (gpa >= 3.0) {
printf("Good standing.\n");
} else if (gpa >= 2.0) {
printf("Satisfactory.\n");
} else {
printf("Academic probation.\n");
}
}
return 0;
}
Ternary Operator (Conditional Operator)
Syntax
condition ? value_if_true : value_if_false
Example
#include <stdio.h>
int main() {
int a = 10, b = 20;
int max;
// Using ternary operator
max = (a > b) ? a : b;
printf("Maximum: %d\n", max);
// Equivalent if-else statement
if (a > b) {
max = a;
} else {
max = b;
}
printf("Maximum: %d\n", max);
return 0;
}
When to Use Ternary Operator
- For simple conditional assignments
- When you need a more concise expression
- Avoid for complex conditions as it reduces readability
Common Mistakes and Solutions
Mistake 1: Assignment vs Comparison
// Wrong - uses assignment (=) instead of comparison (==)
if (x = 5) { // This assigns 5 to x, then checks if 5 is true (it is)
printf("This will always execute\n");
}
// Correct - uses comparison
if (x == 5) {
printf("This executes only when x equals 5\n");
}
Mistake 2: Floating-Point Comparison
// Problematic - floating-point precision issues
float f = 0.1f + 0.2f;
if (f == 0.3f) { // May not work as expected
printf("Equal\n");
}
// Better approach
float f = 0.1f + 0.2f;
float epsilon = 0.0001f;
if (fabs(f - 0.3f) < epsilon) {
printf("Equal (within tolerance)\n");
}
Mistake 3: Missing Braces
// Dangerous - only the first statement is part of the if
if (condition)
printf("First line\n");
printf("Second line\n"); // Always executes!
// Correct - use braces
if (condition) {
printf("First line\n");
printf("Second line\n"); // Both lines are part of the if
}
Advanced Examples
Example 1: Comprehensive Number Analysis
#include <stdio.h>
#include <math.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number == 0) {
printf("The number is zero.\n");
} else {
// Check positive/negative
if (number > 0) {
printf("The number is positive.\n");
} else {
printf("The number is negative.\n");
}
// Check even/odd (only for positive numbers)
if (number > 0) {
if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
}
// Check if perfect square
int sqrt_num = (int)sqrt(abs(number));
if (sqrt_num * sqrt_num == abs(number)) {
printf("The number is a perfect square.\n");
}
}
return 0;
}
Example 2: Student Grading System
#include <stdio.h>
int main() {
float attendance, assignment, midterm, final;
float total_score;
char grade;
printf("Enter attendance percentage (0-100): ");
scanf("%f", &attendance);
if (attendance < 75) {
printf("Insufficient attendance. Cannot award grade.\n");
return 1;
}
printf("Enter assignment score (0-100): ");
scanf("%f", &assignment);
printf("Enter midterm score (0-100): ");
scanf("%f", &midterm);
printf("Enter final exam score (0-100): ");
scanf("%f", &final);
// Calculate weighted total (assignments 30%, midterm 30%, final 40%)
total_score = (assignment * 0.3) + (midterm * 0.3) + (final * 0.4);
if (total_score >= 90) {
grade = 'A';
} else if (total_score >= 80) {
grade = 'B';
} else if (total_score >= 70) {
grade = 'C';
} else if (total_score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
printf("\n=== GRADE REPORT ===\n");
printf("Attendance: %.1f%%\n", attendance);
printf("Total Score: %.2f\n", total_score);
printf("Grade: %c\n", grade);
if (grade == 'F') {
printf("Status: FAIL\n");
} else if (grade >= 'A' && grade <= 'C') {
printf("Status: PASS with %s performance\n",
(grade == 'A') ? "excellent" :
(grade == 'B') ? "good" : "satisfactory");
} else {
printf("Status: PASS\n");
}
return 0;
}
Summary
The if-else statement is a fundamental control structure that enables decision-making in C programs. It allows programs to execute different code blocks based on conditions, making programs dynamic and responsive to different inputs and situations. Key concepts include basic if statements for simple conditions, if-else for binary decisions, if-else-if ladders for multiple conditions, and nested if-else for complex decision trees. Understanding comparison and logical operators is essential for creating effective conditions. Best practices include using braces consistently, maintaining reasonable nesting levels, proper indentation, and careful consideration of condition order in if-else-if ladders. Common pitfalls include confusing assignment with comparison, floating-point comparison issues, and scope problems with missing braces. Mastering if-else statements is essential for progressing to more advanced programming concepts and building sophisticated program logic that can handle real-world scenarios effectively.
Part of BCA Programming with C Course (UGCOA22J201)