C Lesson 10 – Control Statements | Dataplexa

Control Statements in C

Till now, our programs were executing line by line without any decision making. But real programs must take decisions.

Control statements allow the program to choose which block of code should run based on conditions.


What Are Control Statements?

Control statements decide the flow of execution in a program. They control:

  • Which statements execute
  • When they execute
  • Under what condition they execute

In this lesson, we focus on:

  • if statement
  • if–else statement

The if Statement

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

Syntax:


if (condition) {
    // code executes if condition is true
}

Simple Example Using if


#include <stdio.h>

int main() {
    int age = 20;

    if (age >= 18) {
        printf("You are eligible to vote");
    }

    return 0;
}

Here:

  • The condition age >= 18 is checked
  • If true, the message is printed

The if–else Statement

The if–else statement executes one block if the condition is true, otherwise another block.

Syntax:


if (condition) {
    // executes if condition is true
} else {
    // executes if condition is false
}

Numerical Example: Even or Odd


#include <stdio.h>

int main() {
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    if (num % 2 == 0) {
        printf("Even number");
    } else {
        printf("Odd number");
    }

    return 0;
}

This program:

  • Reads a number from the user
  • Checks the remainder using %
  • Decides even or odd

Real-World Thinking

Control statements work like daily decisions:

  • If it rains → take umbrella
  • If marks ≥ pass mark → pass else fail
  • If balance ≥ amount → withdraw else deny

Computers follow the same logic.


Common Mistakes

  • Using = instead of ==
  • Missing curly braces
  • Wrong logical condition

These mistakes cause incorrect decisions.


Mini Practice

  • Check whether a number is positive or negative
  • Check if a person is eligible for driving license
  • Compare two numbers and print the greater one

Quick Quiz

Q1. What does the if statement do?

It executes code only when a condition is true.

Q2. When does else block execute?

When the if condition is false.

Q3. Which operator checks equality?

The == operator.

Q4. What does num % 2 check?

It checks whether a number is even or odd.

Q5. Can an if statement exist without else?

Yes, else is optional.