0
0
Cprogramming~5 mins

If statement in C

Choose your learning style9 modes available
Introduction

An if statement helps your program make decisions by choosing what to do based on a condition.

To check if a number is positive or negative.
To decide if a user is old enough to access a website.
To perform an action only when a button is clicked.
To check if a password entered is correct.
Syntax
C
if (condition) {
    // code to run if condition is true
}

The condition is a test that is either true or false.

If the condition is true, the code inside the braces runs.

Examples
This checks if x is greater than zero and prints a message if true.
C
if (x > 0) {
    printf("x is positive\n");
}
This checks if age is 18 or more to allow voting.
C
if (age >= 18) {
    printf("You can vote\n");
}
This checks if score equals 100 exactly.
C
if (score == 100) {
    printf("Perfect score!\n");
}
Sample Program

This program checks if the variable number is positive and prints a message if it is.

C
#include <stdio.h>

int main() {
    int number = 10;

    if (number > 0) {
        printf("The number is positive.\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Always use parentheses around the condition.

Curly braces { } are needed to group the code that runs when the condition is true.

If you forget braces and write only one statement, it still works but can cause bugs if you add more later.

Summary

An if statement lets your program choose actions based on conditions.

Use parentheses for the condition and braces for the code block.

The code inside runs only if the condition is true.