If Statement in C

Conditions • Decision-Making • Program Flow Control

1. Introduction to Decision Making

Programs often need to choose between multiple paths of execution. In C, decision-making is done using the if family of statements.

The if statement checks a condition (true/false) and executes code only when the condition is true.

Conditions typically use:

  • Relational operators: > < >= <= == !=
  • Logical operators: && || !

2. Basic if Statement

The simplest form executes a block only if the condition is true.

if (condition) {
    // code runs when condition is true
}
Example
#include <stdio.h>

int main() {

    int age = 20;

    if (age >= 18) {
        printf("You are an adult.\n");
    }

    return 0;
}

Output: You are an adult.

3. if…else Statement

Use this when you need to choose between two actions.

if (condition) {
    // true block
} else {
    // false block
}
Example
#include <stdio.h>

int main() {

    int n = -5;

    if (n >= 0) {
        printf("Positive\n");
    } else {
        printf("Negative\n");
    }

    return 0;
}

4. else if Ladder

Used when there are multiple possible conditions.

#include <stdio.h>

int main() {

    int marks = 82;

    if (marks >= 90) {
        printf("Grade A\n");
    }
    else if (marks >= 75) {
        printf("Grade B\n");
    }
    else if (marks >= 50) {
        printf("Grade C\n");
    }
    else {
        printf("Fail\n");
    }

    return 0;
}

5. Nested if Statements

You can place one if statement inside another.

#include <stdio.h>

int main() {

    int a = 10;

    if (a > 0) {
        if (a % 2 == 0) {
            printf("Positive Even\n");
        }
    }

    return 0;
}

6. Comparison of All Types

Type Use Case
ifSingle condition
if…elseTwo-way decision
else ifMultiple conditions
Nested ifDecision inside another decision

7. Example Program

#include <stdio.h>

int main() {
    int temp;

    printf("Enter temperature: ");
    scanf("%d", &temp);

    if (temp > 40) {
        printf("Very Hot");
    }
    else if (temp > 30) {
        printf("Hot");
    }
    else if (temp > 20) {
        printf("Warm");
    }
    else {
        printf("Cold");
    }

    return 0;
}

Try Code in Online Compiler