Skip to content
Bootpoot

Technology moves fast.
Stay curious. Keep learning.

Eduction

C programming if else statement

By Harshit Kumar2 min read
C programming if else statement

In C, an if–else statement chooses between two blocks. A nonzero condition runs the if block. A zero condition runs the else block. Use this pattern when you need exactly one of two outcomes.

A complete if–else example in C

#include <stdio.h>

int main(void)
{
    int number;
    printf("Enter an integer: ");

    if (scanf("%d", &number) != 1) {
        puts("Invalid input");
        return 1;
    }

    if (number % 2 == 0) {
        puts("Even");
    } else {
        puts("Odd");
    }
    return 0;
}

The first if checks whether input was read successfully. The second checks whether dividing the number by two leaves a remainder of zero. Enter 8 and the program prints Even. Enter 7 or -3 and it prints Odd. Zero is even, so entering 0 prints Even. Entering hello reaches the input error instead.

Three common mistakes

  • Assignment in the condition. Use == to compare values. A single = assigns a value.
  • A stray semicolon. In if (condition);, the statement controlled by if is empty. Remove the semicolon and put the intended statements inside braces.
  • Two independent tests. A second if is evaluated separately. Use else when the second path should run only if the first condition is false.

When two branches aren’t enough

To distinguish positive numbers, negative numbers, and zero, test number > 0, then use else if (number < 0), and put the zero case in the final else. Each input reaches exactly one branch. For more patterns, compare conditional statements in C or try the leap-year exercise.

Read more