# 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**:

   ```c
   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**:

   ```c
   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**:

   ```c
   if (condition) {
       // Block executed if condition is TRUE
   }
   else {
       // Block executed if condition is FALSE
   }
   ```
3. **Flow**: One and only one of the two blocks will be executed.
4. **Example**:

   ```c
   int number = 7;
   if (number % 2 == 0) {
       printf("%d is even.\n", number);
   }
   else {
       printf("%d is odd.\n", number);
   }
   ```

#### 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.

   ```c
   if (marks >= 50) {
       if (marks >= 80) {
           printf("Distinction\n");
       }
       else {
           printf("Pass\n");
       }
   }
   else {
       printf("Fail\n");
   }
   ```
2. **The `else-if` Ladder**: A clean way to check multiple conditions in sequence.
   * **Syntax**:

     ```c
     if (condition1) {
         // Block 1
     }
     else if (condition2) {
         // Block 2
     }
     else if (condition3) {
         // Block 3
     }
     // ... more else-if blocks
     else {
         // Default block if all conditions are false
     }
     ```
   * **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)**:

     ```c
     int score = 85;
     if (score >= 90) {
         printf("Grade: A\n");
     }
     else if (score >= 80) {
         printf("Grade: B\n"); // This block executes for score=85
     }
     else if (score >= 70) {
         printf("Grade: C\n");
     }
     else {
         printf("Grade: F\n");
     }
     ```

#### 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**:

   ```c
   switch (expression) {
       case constant1:
           // Statements for constant1
           break;
       case constant2:
           // Statements for constant2
           break;
       // ... more cases
       default:
           // Statements if no case matches
   }
   ```
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**:

   ```c
   char choice;
   printf("Enter a, b, or c: ");
   scanf(" %c", &choice);

   switch (choice) {
       case 'a':
           printf("You chose option A.\n");
           break;
       case 'b':
           printf("You chose option B.\n");
           break;
       case 'c':
           printf("You chose option C.\n");
           break;
       default:
           printf("Invalid choice.\n");
   }
   ```

***

### 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**:

   ```c
   for (initialization; condition; update) {
       // Body of the loop (statements to repeat)
   }
   ```
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)**:

   ```c
   int i;
   for (i = 1; i <= 5; i++) {
       printf("%d ", i);
   }
   // Output: 1 2 3 4 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**:

   ```c
   while (condition) {
       // Body of the loop
   }
   ```
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)**:

   ```c
   int num = 1234, sum = 0, digit;
   while (num != 0) {
       digit = num % 10; // Get last digit
       sum += digit;
       num = num / 10;   // Remove last digit
   }
   printf("Sum of digits: %d\n", sum); // Output: 10
   ```

#### 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**:

   ```c
   do {
       // Body of the loop
   } while (condition);
   ```

   **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**:

   ```c
   int user_input;
   do {
       printf("Enter a positive number: ");
       scanf("%d", &user_input);
   } while (user_input <= 0); // Repeat until user enters a positive number
   printf("You entered: %d\n", user_input);
   ```

#### 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)**:

   ```c
   int num;
   while (1) { // Infinite loop structure
       printf("Enter a number (negative to quit): ");
       scanf("%d", &num);
       if (num < 0) {
           break; // Terminates the while loop
       }
       printf("You entered: %d\n", num);
   }
   printf("Loop ended.\n");
   ```

#### 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)**:

   ```c
   int i;
   for (i = 1; i <= 10; i++) {
       if (i % 2 == 0) {
           continue; // Skip the printf for even numbers
       }
       printf("%d ", i); // This line is only reached for odd numbers
   }
   // Output: 1 3 5 7 9
   ```

#### 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.
