Comprehensive Study Guide on Control Structures in C

Overview of Unit 2: Control Structures

  • Subject: Computer Programming & C Language

  • Unit: Unit 2 — Control Structures

  • Allocated Time: 8 Hours

  • Core Concepts Covered:

    • Decision Control Structures: if, if-else, else-if ladder, conditional operator statement (? :), switch-case statement.

    • Loop Control Structures: for, while, do-while loops.

    • Nested Control Structures: Nested if and nested loops.

    • Jump Statements: break, continue, goto and their practical uses.

    • Problem Solving: Comprehensive examples and logic-building steps involving basic control structures.

    • Case Study #3: Performance comparison of if-else versus switch-case constructs in scenarios such as grading systems, analyzing scalability, compiler jump-table optimization, and code maintainability.

Decision Control Structures

Fundamentals of Decision Making in C

  • By default, C program statements execute sequentially from top to bottom.

  • Decision-making (conditional) statements are utilized to control the execution flow of a program based on specific criteria.

  • They enable conditional execution, allowing the program to decide whether a particular block of code should execute or be bypassed.

  • Evaluation Mechanism:

    1. The decision statement evaluates a relational or logical expression (condition).

    2. The condition yields either a true (non-zero) or false (zero) logical result.

    3. Based on the evaluated result, program control is transferred dynamically to a designated branch or statement path.

Conditional Statements in C Hierarchy

Classification of Decision Making Statements

  • One-Way Decision: if statement.

  • Two-Way Decision: if...else statement and Conditional Operator (? :).

  • Multi-Way / n-Way Decision: if...else if...else ladder and switch...case statement.

The if Statement

  • The if statement is a single-branch decision-making construct.

  • The keyword if signals the start of the construct.

  • Execution Rule: The body within the if block is executed if and only if the specified condition evaluates to true (non-zero). If the condition evaluates to false (zero), the body is skipped entirely, and execution resumes at the subsequent program statement.

  • Syntax: c if (condition) { // Body of if (executed only when condition is true) }     

  • Braces {} Policy:

    • If the body of the if construct contains only a single statement, curly braces {} are optional.

    • If the body contains two or more statements, curly braces {} are strictly mandatory to group them into a compound statement.

if Statement Examples
  • Example 1: Print Zero if Given Number is 0 ```c

    include

    void main() { int a; printf("Enter Number:"); scanf("%d", &a); if (a == 0) { printf("Zero"); } }     ```

    • Sample Output 1: text Enter Number:0 Zero         

  • Example 2: Print Positive or Negative Number using Independent if Statements ```c

    include

    void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a >= 0) { printf("Positive Number"); } if (a < 0) { printf("Negative Number"); } }     ```

    • Sample Output 1: text Enter Number:5 Positive Number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Sample Output 2: text Enter Number:-5 Negative Number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Example 3: Print Odd or Even Number using Independent if Statements ```c

    include

    void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a % 2 == 0) { printf("Even Number"); } if (a % 2 != 0) { printf("Odd Number"); } }     ```

    • Sample Output 1: text Enter Number:12 Even Number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Sample Output 2: text Enter Number:11 Odd Number &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Example 4: Find Largest Number from 2 Given Numbers using Independent if Statementsc #include <stdio.h> void main() { int a, b; printf("Enter Two Numbers:"); scanf("%d %d", &a, &b); if (a > b) { printf("%d is largest", a); } if (a < b) { printf("%d is largest", b); } } &nbsp;&nbsp;&nbsp;&nbsp;

    • Sample Output: text Enter Two Numbers:4 5 5 is largest &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

The if...else Statement

  • The if...else construct provides a two-branch decision-making structure.

  • else is a reserved C keyword.

  • Execution Rule: If the condition evaluates to true, the if branch body is executed. If the condition evaluates to false, execution bypasses the if body and executes the else branch body instead. Under no circumstance are both bodies executed in a single evaluation.

  • Syntax: c if (condition) { // True part execution } else { // False part execution } &nbsp;&nbsp;&nbsp;&nbsp;

if...else Statement Examples
  • Example 1: Positive or Negative Number Determination ```c

    include

    void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a >= 0) { printf("Positive Number"); } else { printf("Negative Number"); } }     ```

  • Example 2: Odd or Even Number Determination ```c

    include

    void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a % 2 == 0) { printf("Even Number"); } else { printf("Odd Number"); } }     ```

  • Example 3: Find Largest Number from 2 Numbersc #include <stdio.h> void main() { int a, b; printf("Enter Two Numbers: "); scanf("%d %d", &a, &b); if (a > b) { printf("%d is largest", a); } else { printf("%d is largest", b); } } &nbsp;&nbsp;&nbsp;&nbsp;

The if...else if...else Ladder

  • The else if ladder is a multi-branch decision construct suitable for evaluating multiple sequential conditions.

  • Evaluation Strategy:

    1. Sequential conditions are tested top-down starting from condition-1.

    2. As soon as any condition evaluates to true, its associated statement block executes, and the remainder of the entire ladder is bypassed entirely.

    3. If condition-1 is false, condition-2 is evaluated. This process continues down the ladder.

    4. If none of the tested conditions evaluate to true, the final trailing else statement block executes as the default fall-through branch.

  • Syntax: c if (condition-1) statement-1; else if (condition-2) statement-2; else if (condition-3) statement-3; else default-statement; &nbsp;&nbsp;&nbsp;&nbsp;

if...else if...else Ladder Examples
  • Example 1: Classify Number as Zero, Positive, or Negativec #include <stdio.h> void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a > 0) { printf("Positive Number"); } else if (a == 0) { printf("Zero"); } else { printf("Negative Number"); } } &nbsp;&nbsp;&nbsp;&nbsp;

Nested if Statements

  • A nested if refers to placing an if or if...else structure inside another if or else block.

  • Execution Logic:

    • An inner condition (condition-2) is evaluated if and only if the primary outer condition (condition-1) evaluates to true.

    • If condition-1 is false, execution shifts immediately to the outer else branch (statement-3).

  • Syntax: c if (condition-1) { if (condition-2) { statement-1; } else { statement-2; } } else { statement-3; } &nbsp;&nbsp;&nbsp;&nbsp;

Nested if Examples
  • Example 1: Find Maximum Among Three Numbersc #include <stdio.h> void main() { int a, b, c; printf("Enter Three Numbers: "); scanf("%d %d %d", &a, &b, &c); if (a > b) { if (a > c) printf("%d is max", a); else printf("%d is max", c); } else { if (b > c) printf("%d is max", b); else printf("%d is max", c); } } &nbsp;&nbsp;&nbsp;&nbsp;

    • Sample Output: text Enter Three Numbers:7 5 9 9 is max &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

The Conditional Operator (? :)

  • The conditional operator is C's only ternary operator (requiring three operands).

  • It offers a compact alternative to simple if-else constructs.

  • Structure: variable = Expression1 ? Expression2 : Expression3

    • Expression1 is the condition to evaluate.

    • If Expression1 evaluates to true (non-zero), Expression2 is evaluated, and its value is assigned/returned.

    • If Expression1 evaluates to false (zero), Expression3 is evaluated, and its value is assigned/returned.

Conditional Operator Examples
  • Example 1: Find Largest of Two Numbersc #include <stdio> void main() { int a, b, max; printf("Enter Two Numbers:"); scanf("%d %d", &a, &b); max = (a > b) ? a : b; printf("%d is largest", max); } &nbsp;&nbsp;&nbsp;&nbsp;

The switch...case Statement

  • The switch statement provides a multi-way selective branching mechanism that allows a variable or expression to be tested against a set of integer/character constant values.

  • Behavioral Rules:

    1. The control expression inside switch(expression) is evaluated once and compared sequentially against the values in each case constant: label.

    2. The expression must yield an integral or character evaluation (floating-point expressions are prohibited).

    3. If an exact match is identified, program execution jumps directly to the matching case block.

    4. Fall-Through Effect: Without an explicit break; statement terminating a case block, control continues executing into subsequent case blocks regardless of whether those labels match.

    5. The default: block is optional and executes when no matching constant matches the switch expression.

  • Syntax: c switch (expression) { case constant1: // statements break; case constant2: // statements break; default: // default statements executed if no match } &nbsp;&nbsp;&nbsp;&nbsp;

switch...case Examples
  • Example 1: Map Day Number (1–7) to Day Namec #include <stdio.h> void main() { int day; printf("Enter day number (1-7):"); scanf("%d", &day); switch (day) { case 1: printf("Sunday"); break; case 2: printf("Monday"); break; case 3: printf("Tuesday"); break; case 4: printf("Wednesday"); break; case 5: printf("Thursday"); break; case 6: printf("Friday"); break; case 7: printf("Saturday"); break; default: printf("Wrong input"); break; } } &nbsp;&nbsp;&nbsp;&nbsp;

    • Sample Output: text Enter day number (1-7):5 Thursday &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Loop Control Structures

Concept and Necessity of Looping

  • A loop control structure enables repeated execution of a specific block of code for a designated number of times or until a defined loop condition evaluates to false.

  • Loops eliminate redundant code replication, optimize memory usage, and improve code modularity.

Taxonomy of Loop Control Structures

  1. Entry-Controlled Loops: Condition is checked prior to executing the loop body.

    • while loop

    • for loop

  2. Exit-Controlled Loops: Loop body executes once before its termination condition is verified at the bottom.

    • do-while loop

  3. Virtual Loop: goto statement (unconditional branch used to emulate iteration).

Methodological Logic Building in Loop Programming

Developing efficient algorithms for loop problems involves a structured 4-step framework:

Step 1: Problem Analysis and Conceptualization
  • Objective: Analyze the requirements completely (e.g., Finding factors of an integer nn).

  • Domain Knowledge: A factor of nn is any integer ii that divides nn completely with zero remainder (n mod i=0n \bmod i = 0).

  • Variable Allocation:

    • Input integer stored in variable n.

    • Loop iterator variable i initialized to start checking from 11.

  • Control Structure Identification:

    • A loop iterator variable ii running sequentially from 11 up to nn.

    • An embedded if construct checking the divisibility condition n % i == 0 during each iteration.

Step 2: Test Case Analysis
  • Test Case 1 (n=6n = 6):

    • 6 mod 1=0→True6 \bmod 1 = 0 \rightarrow \text{True} (1 is a factor)

    • 6 mod 2=0→True6 \bmod 2 = 0 \rightarrow \text{True} (2 is a factor)

    • 6 mod 3=0→True6 \bmod 3 = 0 \rightarrow \text{True} (3 is a factor)

    • 6 mod 4=2→False6 \bmod 4 = 2 \rightarrow \text{False}

    • 6 mod 5=1→False6 \bmod 5 = 1 \rightarrow \text{False}

    • 6 mod 6=0→True6 \bmod 6 = 0 \rightarrow \text{True} (6 is a factor)

    • Inference: Iterator starts at 11, increments by 11, and terminates when i>ni > n.

  • Test Case 2 (n=10n = 10): Factors are 1,2,5,101, 2, 5, 10.

  • Test Case 3 (n=11n = 11): Factors are 1,111, 11 (Prime integer).

  • General Rule: Every positive integer nn has at least 11 and nn as universal factors.

Step 3: Algorithmic Blueprinting and Flowcharting
  • Step 1: Start execution.

  • Step 2: Declare integer variables n, i.

  • Step 3: Initialize iterator variable i→1i \rightarrow 1.

  • Step 4: Read input integer n from user.

  • Step 5: Evaluate loop condition i×ni \times n:

    • If i mod n→Truei \bmod n \rightarrow \text{True}, evaluate sub-condition n % i == 0.

    • If n % i == 0 is True, print value of ii.

    • Increment iterator i→i+1i \rightarrow i + 1.

    • Re-evaluate loop condition.

  • Step 6: Stop execution when loop condition evaluates to False.

Step 4: Pseudo-Code Design

```text
Initialize i = 1 as integer Declare n as integer Input n while i <= n do if n % i == 0 then print i end if i = i + 1 end while

## Structural Distinction: `if` vs `while` Constructs

*   **`if` Statement**: Evaluates condition once. If true, executes the statement block exactly once, then transfers control to subsequent lines.
*   **`while` Loop**: Evaluates condition. If true, executes loop body, and automatically loops control back to re-evaluate condition. Execution repeats iteratively until condition evaluates to false.

## The `while` Loop

*   An **entry-controlled** looping construct.
*   Statements inside the body are repeatedly executed as long as the relational condition evaluates to **true**.

*   **Syntax**:
    ```c
    while (condition)
    {
        // Body of while loop
        // Increment / Decrement statement
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

### `while` Loop Examples and Execution Traces

*   **Example 1: Print Numbers 1 to n**
    ```c
    #include <stdio.h>
    void main()
    {
        int i, n;
        i = 1;
        printf("Enter n: ");
        scanf("%d", &n);
        while (i <= n)
        {
            printf("%d
", i);
            i = i + 1;
        }
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

*   **Example 2: Print Odd Numbers Between 1 to n (with Trace Table)**
    ```c
    #include <stdio.h>
    void main()
    {
        int i = 1, n;
        printf("Enter the value of n");
        scanf("%d", &n);
        while (i <= n)
        {
            if (i % 2 != 0)
            {
                printf("%d
", i);
            }
            i = i + 1;
        }
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

#### Execution Trace Table for Odd Numbers Program (n=5n = 5)

| Line # | `i` | `n` | Condition / Statement | Result | Execution Action / Output | Process Notes |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| 1–5 | - | - | Initial declarations | - | Headers, main startup | Setup program memory |
| 6 | 1 | - | Initializing variable | - | `i` set to 1 | Initial iterator value |
| 7 | 1 | 5 | Input scanning | - | Reads `n = 5` | Value scanned into `n` |
| 8 | 1 | 5 | `i <= n` (`1 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 1 | 5 | `i % 2 != 0` (`1 % 2 != 0`) | **True** | Enter `if` statement block | 1 is odd |
| 10 | 1 | 5 | `printf("%d
", i)` | - | **Output: 1** | Print current odd `i` |
| 11 | 2 | 5 | `i = i + 1` | - | `i` updated to 2 | Increment iterator |
| 8 | 2 | 5 | `i <= n` (`2 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 2 | 5 | `i % 2 != 0` (`2 % 2 != 0`) | **False** | Skip `if` body | 2 is even |
| 11 | 3 | 5 | `i = i + 1` | - | `i` updated to 3 | Increment iterator |
| 8 | 3 | 5 | `i <= n` (`3 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 3 | 5 | `i % 2 != 0` (`3 % 2 != 0`) | **True** | Enter `if` statement block | 3 is odd |
| 10 | 3 | 5 | `printf("%d
", i)` | - | **Output: 3** | Print current odd `i` |
| 11 | 4 | 5 | `i = i + 1` | - | `i` updated to 4 | Increment iterator |
| 8 | 4 | 5 | `i <= n` (`4 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 4 | 5 | `i % 2 != 0` (`4 % 2 != 0`) | **False** | Skip `if` body | 4 is even |
| 11 | 5 | 5 | `i = i + 1` | - | `i` updated to 5 | Increment iterator |
| 8 | 5 | 5 | `i <= n` (`5 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 5 | 5 | `i % 2 != 0` (`5 % 2 != 0`) | **True** | Enter `if` statement block | 5 is odd |
| 10 | 5 | 5 | `printf("%d
", i)` | - | **Output: 5** | Print current odd `i` |
| 11 | 6 | 5 | `i = i + 1` | - | `i` updated to 6 | Increment iterator |
| 8 | 6 | 5 | `i <= n` (`6 <= 5`) | **False** | Terminate loop | Loop exits |
| 13 | 6 | 5 | End of `main()` | - | Returns execution | Program ends successfully |

*   **Example 3: Print Multiplication Table**
    ```c
    #include <stdio.h>
    void main()
    {
        int i = 1, n;
        printf("Enter n for multiplication table:");
        scanf("%d", &n);
        while (i <= 10)
        {
            printf("%d * %d = %d
", n, i, n * i);
            i = i + 1;
        }
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

*   **Example 4: Calculate Sum of 5 User-Entered Numbers**
    ```c
    #include <stdio.h>
    void main()
    {
        int sum = 0, i = 1, n;
        while (i <= 5)
        {
            printf("Enter a number=");
            scanf("%d", &n);
            sum = sum + n;
            i = i + 1;
        }
        printf("Sum is=%d", sum);
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

*   **Example 5: Find Factors of a Number**
    ```c
    #include <stdio.h>
    void main()
    {
        int i = 1, n;
        printf("Enter n to find factors=");
        scanf("%d", &n);
        while (i <= n)
        {
            if (n % i == 0)
            {
                printf("%d,", i);
            }
            i = i + 1;
        }
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

*   **Example 6: Reverse an Integer Value**
    ```c
    #include <stdio.h>
    void main()
    {
        int n;
        printf("Enter a number=");
        scanf("%d", &n);
        while (n != 0)
        {
            printf("%d", n % 10);
            n = n / 10;
        }
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

*   **Example 7: Check if Number is Perfect Number**
    *   *Definition*: A perfect number is a positive integer equal to the sum of its proper positive divisors (excluding itself).
    ```c
    #include <stdio.h>
    void main()
    {
        int i = 1, n, sum = 0;
        printf("Enter a number:");
        scanf("%d", &n);
        while (i < n)
        {
            if (n % i == 0)
            {
                printf("%d+", i);
                sum = sum + i;
            }
            i = i + 1;
        }
        printf("=%d", sum);
        if (sum == n)
            printf("
%d is a perfect number", n);
        else
            printf("
%d is not a perfect number", n);
    }
&nbsp;&nbsp;&nbsp;&nbsp;```
    *   *Sample Output 1*:
        ```text
        Enter a number:6
        1+2+3=6
        6 is a perfect number
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;```
    *   *Sample Output 2*:
        ```text
        Enter a number:8
        1+2+4+=7
        8 is not a perfect number
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;```
    *   *Sample Output 3*:
        ```text
        Enter a number:496
        1+2+4+8+16+31+62+124+248+=496
        496 is a perfect number
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;```

## The `for` Loop

*   An **entry-controlled** loop structure that consolidates initialization, condition testing, and parameter update operations into a single header statement.
*   **Execution Order**:
    1. **Initialization**: Executed exactly once prior to the first loop test.
    2. **Condition Evaluation**: Tested before each iteration. If false, loop terminates.
    3. **Body Execution**: Executed if the condition tests true.
    4. **Update Statement**: Executed at the end of every iteration, immediately prior to re-evaluating the condition.

*   **Syntax**:
    ```c
    for (initialization; condition; updateStatement)
    {
        // Loop body statements
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

### `for` Loop Examples

*   **Example 1: Print Numbers 1 to n**
    ```c
    #include <stdio.h>
    void main()
    {
        int i, n;
        printf("Enter a number:");
        scanf("%d", &n);
        for (i = 1; i <= n; i++)
        {
            printf("%d
", i);
        }
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

*   **Example 2: Find Factors of a Number**
    ```c
    #include <stdio.h>
    void main()
    {
        int i, n;
        printf("Enter n to find factors=");
        scanf("%d", &n);
        for (i = 1; i <= n; i++)
        {
            if (n % i == 0)
            {
                printf("%d,", i);
            }
        }
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

*   **Example 3: Check Perfect Number**
    ```c
    #include <stdio.h>
    void main()
    {
        int i, n, sum = 0;
        printf("Enter a number:");
        scanf("%d", &n);
        for (i = 1; i < n; i++)
        {
            if (n % i == 0)
            {
                printf("%d+", i);
                sum = sum + i;
            }
        }
        printf("=%d", sum);
        if (sum == n)
            printf("
%d is a perfect number", n);
        else
            printf("
%d is not a perfect number", n);
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

## The `do-while` Loop

*   An **exit-controlled** looping construct.
*   **Key Property**: The loop body is executed **at least once** regardless of whether the loop condition is initially true or false, because condition verification occurs at the bottom of the loop.

*   **Syntax**:
    ```c
    do
    {
        // Body of do-while loop
    } while (condition);
&nbsp;&nbsp;&nbsp;&nbsp;```
&nbsp;&nbsp;&nbsp;&nbsp;*(Note: A trailing semicolon `;` after `while(condition)` is mandatory).* 

### `do-while` Loop Examples

*   **Example 1: Print Odd Numbers Between 1 to n**
    ```c
    #include <stdio.h>
    void main()
    {
        int i = 1, n;
        printf("Enter a number: ");
        scanf("%d", &n);
        do
        {
            if (i % 2 != 0)
            {
                printf("%d,", i);
            }
            i = i + 1;
        } while (i <= n);
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

*   **Example 2: Reverse a Given Number**
    ```c
    #include <stdio.h>
    void main()
    {
        int n;
        printf("Enter a number:");
        scanf("%d", &n);
        do
        {
            printf("%d", n % 10);
            n = n / 10;
        } while (n != 0);
    }
&nbsp;&nbsp;&nbsp;&nbsp;```

# Jump Statements in C

*   Jump statements force unconditional dynamic control transfers to another location within the program, bypassing standard structured sequencing.

## The `break` Statement

*   Immediately terminates the execution of the innermost enclosing `for`, `while`, `do-while` loop, or `switch` construct.
*   Program control transfers immediately to the first statement following the terminated control structure.
*   In nested loops, `break` exits **only** the innermost loop layer currently executing.

![Break Statement Flowchart](https://assets.knowt.com/pdf-flow-prod/5329f373-f736-4a15-971d-a8fc3fc8f4d4-figures/13.jpg)

### `break` Code Demonstration

c

include

int main() { int i; for (i = 1; i <= 10; i++) { if (i == 6) { break; } printf("%d ", i); } printf("Loop exited. "); return 0; }

*   *Output*: `1 2 3 4 5 Loop exited.`

## The `continue` Statement

*   Skips all remaining statements in the **current iteration** of a `for`, `while`, or `do-while` loop body.
*   Control transfers immediately to the loop update/condition step for the next iteration.

![Continue Statement Flowchart](https://assets.knowt.com/pdf-flow-prod/5329f373-f736-4a15-971d-a8fc3fc8f4d4-figures/14.jpg)

### `continue` Code Demonstration

c

include

int main() { int i; for (i = 0; i < 5; i++) { if (i == 2) { printf("Skipping iteration %d ", i); continue; } printf("Executing iteration %d ", i); } return 0; } ```

  • Output: text Executing iteration 0 Executing iteration 1 Skipping iteration 2 Executing iteration 3 Executing iteration 4 &nbsp;&nbsp;&nbsp;&nbsp;

The goto Statement

  • Provides an unconditional jump from the goto statement directly to a designated labeled statement within the same function scope.

  • Syntactic Constructs:

    • Forward Jump: c goto label_name; // ... label_name: // statement execution resumes here &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Backward Jump: c label_name: // statement execution target // ... goto label_name; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Engineering Note: Unrestricted use of goto generates unmaintainable control flow ("spaghetti code"). Its usage is limited to exiting deeply nested loops or handling unified function failure cleanup routines.

Goto Statement Flowchart
goto Code Examples
  • Example 1: Print Odd Numbers Between 1 to n Using goto ```c

    include

    void main() { int i = 1, n; printf("Enter a number:"); scanf("%d", &n); odd: if (i % 2 != 0) { printf("%d,", i); } i = i + 1; if (i <= n) { goto odd; } }     ```

  • Example 2: Find Factors of a Number Using gotoc #include <stdio.h> void main() { int i = 1, n; printf("Enter a number:"); scanf("%d", &n); odd: if (n % i == 0) { printf("%d,", i); } i = i + 1; if (i <= n) { goto odd; } } &nbsp;&nbsp;&nbsp;&nbsp;

Comparative Analysis & Practical Applications

Case Study #3: Performance & Architecture — if-else vs. switch-case Constructs

  • Scenario Context: Designing an enterprise automated grading system evaluating student marks across multiple discrete thresholds (A,B,C,D,FA, B, C, D, F).

Computational Complexity and Execution Performance
  • if-else Ladder: Executes sequentially (O(N)O(N) time complexity). Every preceding condition must evaluate to false before testing subsequent conditions. In large decision trees, worst-case execution time grows linearly with branch count.

  • switch-case Construct: When compiled with multiple contiguous cases, modern compilers synthesize an optimized Jump Table (array of code pointers) or Binary Search Tree. Jump tables achieve constant time complexity (O(1)O(1)) execution by calculating memory address offsets directly.

Maintainability, Readability, and Scalability Comparison

Assessment Metrics

if-else Ladder

switch-case Construct

Expression Versatility

Handles complex ranges, floating-point math, and compound logical operations (&&, ||).

Restricted strictly to integer, character constants, and enumerated type equality matching.

Algorithmic Scalability

Degrades in readability and performance as decision branch paths scale into large numbers.

Highly scalable; structured jump tables keep execution speed uniform (O(1)O(1)).

Code Maintainability

Prone to syntax nesting errors; difficult to modify multi-level logical branches safely.

Highly structured modular format; simple to add, remove, or modify isolated case labels.

Control Fall-Through

Bypasses all subsequent blocks automatically upon finding a true condition.

Requires explicit break; statements to prevent unintended case fall-through bugs.

Design Recommendation for Grading Systems
  • For Continuous Range Grading (e.g., 80 to 8980 \text{ to } 89): if-else constructs are idiomatic because standard C switch statements do not natively support continuous variable range comparisons without dynamic condition mapping.

  • For Discrete Grade Scale Processing (e.g., Mapping letter grades 'A', 'B', 'C', 'D', 'F' to distinct administrative procedures): The switch-case pattern provides optimal runtime performance, clean maintainability, and streamlined architecture.