0
0
Cprogramming~5 mins

If–else statement in C

Choose your learning style9 modes available
Introduction

An if-else statement helps your program make choices. It runs one set of instructions if a condition is true, and another set if it is false.

Deciding if a user is old enough to access a website.
Checking if a number is positive or negative.
Choosing what message to show based on the time of day.
Turning on a light if it is dark outside.
Giving a discount if a customer buys more than 5 items.
Syntax
C
if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}
The condition is a test that is either true or false.
Curly braces { } group the code that runs for each case.
Examples
This checks if age is 18 or more. It prints a message based on that.
C
if (age >= 18) {
    printf("You are an adult.\n");
} else {
    printf("You are a minor.\n");
}
This prints "Passed" if score is above 50, otherwise "Failed".
C
if (score > 50) {
    printf("Passed\n");
} else {
    printf("Failed\n");
}
Sample Program

This program asks the user to enter a number. It then checks if the number is even or odd using the if-else statement and prints the result.

C
#include <stdio.h>

int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);

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

    return 0;
}
OutputSuccess
Important Notes

Always use curly braces { } even if you have only one line inside if or else. It helps avoid mistakes.

The condition inside if must be something that can be true or false, like comparisons.

Summary

If-else lets your program choose between two paths.

Use it when you want to do one thing if a condition is true, and another if it is false.

Remember to write clear conditions and use braces for readability.