Dr. Roger Ianjamasimanana

A practical guide to if statement in C

By Dr. Roger Ianjamasimanana

1. What is an if statement?

The if statement allows developers to execute code under a given condition. In this lesson, I will give practical examples of if statement in C.

2. Basic syntax of an if statement

The simplest form of an if statement evaluates a condition and executes a block of code if the condition is true.

if (condition) {
    // code to execute if condition is true
}

Example

#include <stdio.h>

int main() {
    int number = 10;

    if (number > 0) {
        printf("The number is positive.\n");
    }

    return 0;
}

3. Using else and else if

To handle multiple conditions, else and else if can be used in conjunction with the if statement.

if (condition1) {
    // code if condition1 is true
} else if (condition2) {
    // code if condition2 is true
} else {
    // code if none of the above conditions are true
}
#include <stdio.h>

int main() {
    int score = 75;

    if (score >= 90) {
        printf("Grade: A\n");
    } else if (score >= 80) {
        printf("Grade: B\n");
    } else if (score >= 70) {
        printf("Grade: C\n");
    } else {
        printf("Grade: F\n");
    }

    return 0;
}

4. Nested if statements

Conditions can be nested within each other to handle more complex decision-making scenarios.

if (condition1) {
    if (condition2) {
        // code if both condition1 and condition2 are true
    }
}
#include <stdio.h>

int main() {
    int age = 25;
    int hasLicense = 1;

    if (age >= 18) {
        if (hasLicense) {
            printf("You are eligible to drive.\n");
        } else {
            printf("You need a driver's license to drive.\n");
        }
    } else {
        printf("You are not old enough to drive.\n");
    }

    return 0;
}

5. Common mistake

Omitting braces for single statements

While C allows omitting braces for single statements, it can lead to bugs, especially when adding more statements later.

if (condition)
    printf("Condition is true.\n");
// Adding another statement here without braces can cause unexpected behavior
printf("This always prints.\n");

Proper usage with braces

if (condition) {
    printf("Condition is true.\n");
    // Additional statements
    printf("This also prints only if condition is true.\n");
}

6. Best practices

  • Always use braces: even for single statements, using braces improves readability and reduces errors.
  • Keep conditions simple: Complex conditions can be broken down into multiple if statements or helper functions.
  • Use indentation: proper indentation enhances code readability.
  • Avoid deeply nested ifs: consider using switch statements or other control structures for better clarity.

Example

#include <stdio.h>

int main() {
    int a = 5, b = 10;
    int max = (a > b) ? a : b;
    printf("Maximum value is %d\n", max);
    return 0;
}

feature-top
Readers’ comment
feature-top
Log in to add a comment
🔐 Access