if...else in C Programming

The if statement lets a C program execute code only when a condition is true. Add else for the alternative path, or use an else if ladder when several conditions must be tested in order.

if...else Syntax Top ↑

if (condition) {
    // runs when condition is true
} else {
    // runs when condition is false
}

In C, a condition evaluates as false when its value is zero and true when its value is non-zero. Relational operators such as <, >= and == are commonly used to build conditions.

Basic if...else Example Top ↑

#include <stdio.h>

int main(void) {
    int number;

    printf("Enter a number: ");
    if (scanf("%d", &number) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    if (number <= 10) {
        printf("The number is less than or equal to 10.\n");
    } else {
        printf("The number is greater than 10.\n");
    }

    return 0;
}

Key change: only one of the two blocks runs.

else if Ladder Top ↑

An else if ladder is clearer than deeply nesting several if statements when only one range should match.

#include <stdio.h>

int main(void) {
    int mark;

    printf("Enter a mark from 0 to 100: ");
    if (scanf("%d", &mark) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    if (mark < 0 || mark > 100) {
        printf("Mark must be between 0 and 100.\n");
    } else if (mark >= 80) {
        printf("First Division\n");
    } else if (mark >= 60) {
        printf("Second Division\n");
    } else if (mark >= 40) {
        printf("Third Division\n");
    } else {
        printf("Fail\n");
    }

    return 0;
}

The checks run from the highest range downward. Once one condition is true, the remaining branches are skipped.

Nested if...else Top ↑

#include <stdio.h>

int main(void) {
    int number;

    printf("Enter a non-negative integer: ");
    if (scanf("%d", &number) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    if (number >= 0) {
        if (number % 2 == 0) {
            printf("%d is even.\n", number);
        } else {
            printf("%d is odd.\n", number);
        }
    } else {
        printf("The number is negative.\n");
    }

    return 0;
}

Here the second condition is tested only after the program confirms that the number is non-negative.

Common if...else Mistakes Top ↑

  • Use == to compare values; = assigns a value.
  • Use braces consistently, especially when a block contains more than one statement.
  • Order overlapping range checks carefully.
  • Validate keyboard input before using the value.

More if...else Examples Top ↑

Student grade Highest of three numbers Tariff by consumption range





plus2net.com



18-08-2023

Write an if-else statement to check if the grade is above or equal to 60



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer