Part 2 — Chapter 6

Chapter 6: if / else

Programs often need to make decisions while running. Sometimes a block of code should execute only when a certain condition is true. In C, this is done using conditional statements such as if, else, and else if.

These statements help control the flow of execution based on different conditions.

if Statement

The if statement executes a block of code only if the condition evaluates to true.

Syntax
C
if(condition)
{
    // code executes only if condition is true
}
if-else Statement

The else block executes when the condition inside the if block is false.

Syntax
C
if(condition)
{
    // code if condition is true
}
else
{
    // code if condition is false
}
else-if Ladder

The else if ladder is used when multiple distinct conditions need to be checked in sequence.

Syntax
C
if(condition1)
{
    // code executes if condition1 is true
}
else if(condition2)
{
    // code executes if condition1 is false and condition2 is true
}
else
{
    // default code if all above conditions are false
}

Example Program

main.c
C
#include <stdio.h>

int main()
{
    int marks = 75;

    if(marks >= 40)
    {
        printf("Pass");
    }
    else
    {
        printf("Fail");
    }

    return 0;
}
Program Flowchart
Start marks >= 40? Yes printf("Pass") No printf("Fail") Return 0
Console Output
Pass

How It Works

When an if statement executes, the condition inside if() is evaluated first. If the condition is true (non-zero), the code inside the if block executes. Otherwise, control moves to the else block, if present. Conditions are usually formed using relational operators such as >, <, ==, and !=.

In C, = is used for assignment, while == is used for comparison. Multiple conditions can also be combined using logical operators like && (AND) and || (OR). Curly braces { } define the execution block and are recommended even for single-line statements to improve readability and prevent errors.

Embedded Focus

Conditional statements are widely used in embedded systems to make decisions based on hardware inputs and sensor values. Programs continuously check conditions to control physical devices such as LEDs, motors, sensors, timers, and communication modules.

embedded_control.c
C
if(temp > 50)
{
    turn_on_fan(); // Actuate fan if threshold temperature is reached
}

In embedded programming, if conditions help real-time systems respond dynamically to real-world events, safety thresholds, and hardware signals.

← Chapter 5: Operators Chapter 7: switch case →