4.2 Control Statements

4.2 Control Statements

Introduction to Program Control Flow

Control statements are fundamental constructs that determine the order in which instructions in a program are executed. They allow a program to make decisions, repeat tasks, and branch to different sections of code based on conditions, moving beyond simple sequential execution. This ability to control the flow of execution is what transforms a static list of instructions into a dynamic and intelligent program capable of solving complex problems. This unit covers the primary tools for implementing logic: conditional statements for decision-making and looping constructs for repetition.


1. Conditional Statements

Conditional statements allow a program to choose different paths of execution based on whether a specified condition evaluates to true or false.

1.1 The if Statement

  1. Purpose: To execute a block of code only if a given condition is true.

  2. Syntax:

    if (condition) {
        // Block of statements to execute if condition is TRUE
    }
  3. Flow:

    • The condition is evaluated. It must be a relational or logical expression resulting in true (non-zero) or false (zero).

    • If true, the statements inside the block { } are executed.

    • If false, the block is skipped, and control jumps to the statement after the if block.

  4. Example:

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

1.2 The if-else Statement

  1. Purpose: To execute one block of code if a condition is true, and an alternative block if it is false. It provides a two-way branch.

  2. Syntax:

  3. Flow: One and only one of the two blocks will be executed.

  4. Example:

1.3 Nested if-else and The else-if Ladder

  1. Nested if-else: An if or if-else statement inside another if or else block. Used for multi-level decision making.

  2. The else-if Ladder: A clean way to check multiple conditions in sequence.

    • Syntax:

    • Flow: Conditions are checked from top to bottom. The block corresponding to the first true condition is executed. The rest are skipped. If none are true, the final else block executes.

    • Example (Grading System):

1.4 The switch Statement

  1. Purpose: A multi-way branch statement that selects one of many code blocks to execute based on the value of an integer or character expression. It's often cleaner than a long else-if ladder when comparing the same variable against constant values.

  2. Syntax:

  3. Key Rules:

    • The expression must evaluate to an integer (int, char, enum).

    • Each case label must be a constant (e.g., 1, 'A'), not a variable or range.

    • The break statement is crucial. It terminates the switch block. Without it, execution will "fall through" to the next case statements.

    • The default case is optional and executes if none of the case constants match the expression.

  4. Example:


2. Looping Constructs (Iteration Statements)

Loops are used to execute a block of code repeatedly as long as (or until) a specified condition remains true. They are essential for automating repetitive tasks.

2.1 The for Loop

  1. Purpose: Used when the number of iterations is known beforehand (counter-controlled loop). It combines initialization, condition checking, and update in one line.

  2. Syntax:

  3. Execution Flow:

    1. Initialization: Executed once at the start. Typically used to initialize a loop counter.

    2. Condition Check: Evaluated before each iteration. If true, the loop body executes. If false, the loop terminates.

    3. Body Execution: The statements inside the loop are executed.

    4. Update: Executed after each iteration of the body. Typically increments/decrements the loop counter.

    5. Go back to Step 2 (Condition Check).

  4. Example (Print numbers 1 to 5):

2.2 The while Loop

  1. Purpose: Used when the number of iterations is not known beforehand, but the continuation condition is known (condition-controlled loop). It checks the condition before entering the loop body (pre-test loop).

  2. Syntax:

  3. Execution Flow:

    1. Condition is evaluated.

    2. If true, the loop body executes.

    3. After the body, control goes back to step 1.

    4. If false, the loop is skipped.

  4. Crucial: The body must contain statements that eventually make the condition false; otherwise, an infinite loop occurs.

  5. Example (Sum of digits of a number):

2.3 The do-while Loop

  1. Purpose: Similar to while, but it guarantees that the loop body executes at least once because it checks the condition after the body (post-test loop).

  2. Syntax:

    Note the semicolon (;) after while(condition).

  3. Execution Flow:

    1. The body executes.

    2. Condition is evaluated.

    3. If true, go back to step 1.

    4. If false, exit the loop.

  4. Typical Use Case: Menu-driven programs where you want to show the menu at least once.

  5. Example:

2.4 Comparison of Loops

Feature

for Loop

while Loop

do-while Loop

When to Use

Known number of iterations

Unknown iterations, condition pre-check

Unknown iterations, body must run at least once

Initialization

Inside for( ) statement

Before the loop

Before the loop

Condition Check

At the beginning of each iteration

At the beginning of each iteration

At the end of each iteration

Update

Inside for( ) statement

Inside the loop body

Inside the loop body

Body Execution

Only if condition is true

Only if condition is true

At least once, then while condition is true


3. Loop Control Statements

These statements alter the normal sequential flow of execution within loops (and switch).

3.1 The break Statement

  1. Purpose: To terminate the execution of the innermost switch, for, while, or do-while loop immediately. Control passes to the statement immediately following the terminated block.

  2. Usage:

    • In Loops: Used to exit a loop prematurely based on some condition inside the body.

    • In switch: Used to exit the switch block after a case is executed, preventing fall-through.

  3. Example (Exit loop when a negative number is entered):

3.2 Introduction to The continue Statement

  1. Purpose: To skip the rest of the current iteration of the innermost loop and proceed immediately to the next iteration.

    • In for loop: It jumps to the update expression.

    • In while/do-while loop: It jumps to the condition check.

  2. Effect: It does not terminate the loop; it only skips the statements following continue for that particular iteration.

  3. Example (Print only odd numbers from 1 to 10):

3.3 Key Difference: break vs continue

  • break: Exits the loop entirely. No more iterations occur.

  • continue: Skips the current iteration and moves to the next iteration of the same loop.


Conclusion: Control statements are the decision-making and automation engines of a program. Mastering if-else and switch allows you to build intelligent, branching logic. Proficiency with for, while, and do-while loops enables you to handle repetitive tasks efficiently. Understanding break and continue gives you fine-grained control over these repetitive processes. Combining these constructs allows programmers to model complex real-world logic and solve a vast array of computational problems.

Last updated