C if, if-else, else-if Statements – Mastering Conditional Logic

Conditional statements in C allow your program to make decisions and execute code based on conditions. These statements form the foundation of logic and control flow in C programming.

C if Statement

The if statement runs a block of code only if the condition is true.

Syntax:

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

 Example:

#include <stdio.h>

int main() {
    int age = 20;
    if (age >= 18) {
        printf("You are eligible to vote.\n");
    }
    return 0;
}

C if-else Statement

The if-else structure gives a binary choice — one block runs if the condition is true, the other if it’s false.

 Syntax:

if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}

 Example:

#include <stdio.h>

int main() {
    int marks = 45;
    if (marks >= 50) {
        printf("Pass\n");
    } else {
        printf("Fail\n");
    }
    return 0;
}

C else-if Ladder

Use else if to check multiple conditions in sequence. Only the first true condition’s block is executed.

Syntax:

if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none are true }

Example:
#include <stdio.h>

int main() {
    int score = 85;

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

    return 0;
}

Key Points to Remember

StatementPurpose
ifExecutes code if condition is true
if-elseAdds an alternative path
else-ifChecks multiple conditions
elseDefault block if none match

Real-Life Use Case – Login Check

#include <stdio.h>
#include <string.h>

int main() {
    char password[20];
    printf("Enter password: ");
    scanf("%s", password);

    if (strcmp(password, "admin123") == 0) {
        printf("Access Granted\n");
    } else {
        printf("Access Denied\n");
    }

    return 0;
}

Best Practices

TipWhy It Matters
Use braces {} even for single linesAvoids bugs and increases readability
Keep conditions simpleEasier to debug and maintain
Avoid deeply nested if blocksRefactor into functions for clarity

Common Mistakes

MistakeProblem
Missing braces in multi-line codeOnly the first line runs — leads to logic bugs
Using = instead of ==Assigns value instead of comparing
Complex conditions without commentsMakes logic hard to follow