Skip to main content

If Else Statement in C

2 min read Updated May 29, 2025
Share:
On this page (14sections)

About this page

This is a tutorial in C Controls — syntax and concepts for if, if-else, and nested conditions. For runnable code, see the example programs: If Statement and If else.

Introduction

Decision control statements let your program choose different paths based on conditions. The if and if-else statements are the most fundamental decision constructs in C.

if Statement

Executes a block only when the condition is true (non-zero):

if (condition) {
    /* statements */
}

Example

#include <stdio.h>

int main(void) {
    int marks = 75;

    if (marks >= 40)
        printf("Pass\n");

    return 0;
}

if-else Statement

Provides an alternative when the condition is false:

if (condition) {
    /* true block */
} else {
    /* false block */
}

Example

#include <stdio.h>

int main(void) {
    int num = 7;

    if (num % 2 == 0)
        printf("%d is even\n", num);
    else
        printf("%d is odd\n", num);

    return 0;
}

Sample Output

7 is odd

if-else-if Ladder

Test multiple conditions in order:

#include <stdio.h>

int main(void) {
    int score = 82;

    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;
}

Sample Output

Grade: B

Nested if

An if inside another if:

int age = 20;
int hasLicense = 1;

if (age >= 18) {
    if (hasLicense)
        printf("Can drive\n");
    else
        printf("Need a license\n");
}

Best Practices

  • Use braces {} even for single-line blocks.
  • Put the most likely condition first in an if-else-if chain.
  • Keep conditions simple — extract complex logic into variables or functions.
  • Use else if instead of nested if when checking ranges.

Common Mistakes

  • Using = instead of == in conditions (if (x = 5) assigns, not compares).
  • Dangling else — always use braces to make nesting clear.
  • Forgetting that 0 is false and any non-zero value is true in C.

Practice with our If Statement and If else example programs.

Frequently Asked Questions

What is the difference between if and if-else?
if executes a block only when the condition is true. if-else adds an alternative block that runs when the condition is false.
Can I omit braces for a single statement?
Yes, but braces are recommended — they prevent bugs when you add a second statement later.

Related Tutorials

Search tutorials