If statement in C

So far in our journey of learning C programming, we learned to write simple C programs, that executes in the sequence we write. A program that always executes in same sequence is worthless. The ability to control program flow and statements execution is worth.

if statement allows us to select an action based on some condition. It gives programmer to take control over a piece of code. Programmer can control the execution of code based on some condition or user input. For example – if user inputs valid account number and pin, then allow money withdrawal.

If statement works like “If condition is met, then execute the task”. It is used to compare things and take some action based on the comparison. Relational and logical operators supports this comparison.

If statement perform action based on boolean expression true or false.

What is a Boolean expression?

A C expression that evaluates either true or false is known as Boolean expression. However, in C programming there is no concept of true or false value.

In C we represent true with a non-zero integer and false with zero. Hence, in C if an expression evaluates to integer is considered as Boolean expression.

Syntax of if statement

if(boolean_expression)
{
    // body of if
}

In above syntax if boolean expression evaluates true, then statements inside if body executes otherwise skipped.

Flowchart of if statement

if statement flow chart

Example program of if statement

Let us write our first program based on conditions. Write a program to input user age and check if he is eligible to vote in India or not. A person in India is eligible to vote if he is 18+.

/**
 * C program to check if a person is eligible to vote or not.
 */

#include <stdio.h>

int main()
{
    /* Variable declaration to store age */
    int age;

    /* Input age from user */
    printf("Enter your age: ");
    scanf("%d", &age);

    /* Use relational operator to check age */
    if(age >= 18)
    {
        /* If age is greater than or equal 18 years */
        printf("You are eligible to vote in India.");
    }

    return 0;
}

Try some more exercises on if statement

Practice exercises – If else programming exercises in C.

Output

Enter your age: 24
You are eligible to vote in India.

Single vs compound statement inside if body

If there is only single statement inside if body, then braces { } are optional. However, braces after if statement is mandatory, when body of if contains more than one statement.

So, you can write an if condition in two ways.

if(boolean_expression)
    // Single statement inside if
if(boolean_expression)
{
    // Statement 1
    // Statement 2
    ...
    ...
    // Statement n
}

There may happen situations when you want to perform single task inside if. For example – If it is Saturday or Sunday, then employee should not login today. If a student got more than 80 marks, then he passed with distinction. In such situations you can ignore braces {}.