PadhaikoAll subjects

Control Structures

Computer Programming (ENCT 101)

Open in the Padhaiko app

5.1 Introduction to simple and compound statement

In C, programs execute instructions composed of statements.


5.2 Sequential statement

In sequential execution, statements execute one after another strictly in the order they appear from top to bottom, with no branching or repetition.

Sequential Control Flow ExampleC
#include <stdio.h>

int main(void) {
    double c = 25.0;
    double f = (9.0 / 5.0) * c + 32.0;   /* executes first */
    printf("%.1f C = %.1f F\n", c, f);   /* executes second */
    return 0;                            /* executes third */
}

5.3 Branching statement

Branching (selection / decision-making) statements test a condition and transfer control along different execution paths depending on whether the condition is true (non-zero) or false (0).

5.3.1 Simple if statement

Executes a statement or block only when the condition is non-zero (true); otherwise skips it.

Simple if Syntax and ExampleC
if (condition) {
    /* executes when condition is non-zero */
}

if (marks >= 40) {
    printf("Passed\n");
}

5.3.2 if-else statement

Provides two mutually exclusive paths: one executes when condition is true, and the else branch executes when condition is false.

if-else Example: Even or OddC
if (n % 2 == 0) {
    printf("%d is even\n", n);
} else {
    printf("%d is odd\n", n);
}

5.3.3 Nested if-else statement

Placing an if or if-else inside another if or else block handles multi-stage dependent conditions.

5.3.4 else-if ladder

Used when testing a sequence of mutually exclusive conditions from top to bottom. As soon as one condition evaluates true, its block runs and the rest of the ladder is skipped; the trailing else acts as the default fallback.

Grade Classification with else-if LadderC
if (score >= 80) {
    grade = 'A';
} else if (score >= 65) {
    grade = 'B';
} else if (score >= 50) {
    grade = 'C';
} else if (score >= 40) {
    grade = 'D';
} else {
    grade = 'F';
}

5.3.5 switch statement

The switch statement selects among multiple constant integer or character branches (case) based on the value of an integral expression (int, char, enum).

Rules and Behavior of switch-case
FeatureRule in C
Control ExpressionMust evaluate to an integer or character (float/double and strings are invalid)
Case LabelsMust be unique compile-time constant expressions (e.g., case 1:, case 'A':)
Fall-Through & breakExecution falls through into subsequent case blocks unless terminated by break;
Default Casedefault: runs if no case matches (optional, usually placed last)
Aspectelse-if Ladderswitch Statement
Condition TypesSupports ranges (x >= 50), floats, logical &&/||, and inequalitiesTests equality against integer/char constants only
Readability for MenusVerbose when comparing one variable to 5+ fixed optionsClean, structured multi-way dispatch
Execution TransferEvaluates conditions sequentially top to bottomCan compile into a jump table; uses break to prevent fall-through

5.3.6 go to statement

The goto statement performs an unconditional jump to a labeled statement within the same function:

Syntax of gotoC
    if (error_flag) {
        goto cleanup;
    }
    /* normal code */
cleanup:
    printf("Releasing resources.\n");

Excessive use of goto creates tangled "spaghetti code" that is hard to trace and debug. In structured C programming, prefer if, loops, break, and continue; reserve goto only for rare error-cleanup exits out of deeply nested loops.


5.4 Looping statement

A loop (iteration statement) repeats a block of code while a continuation condition remains true. Every well-formed loop has four elements: initialization, termination test, loop body, and update step.

5.4.1 for loop

Ideal when the number of iterations is known beforehand or follows a clean counter pattern.

Syntax: for (initialization; condition; update) { body }

Execution order:

  1. initialization executes once before the loop begins.
  2. condition is tested; if false (0), the loop terminates immediately.
  3. body executes.
  4. update executes, and control returns to testing condition.

5.4.2 while loop

An entry-controlled loop best suited when the number of iterations is unknown in advance (such as reading until a sentinel value). The condition is checked before each iteration; if initially false, the body runs zero times.

while Loop StructureC
while (condition) {
    /* executes 0 or more times */
}

5.4.3 do while

An exit-controlled loop that executes its body first, then tests the condition at the bottom. Therefore, the body always runs at least once, even if the condition is initially false. Notice the mandatory semicolon ; after while (condition);.

Aspectwhile Loop (Entry-Controlled)do-while Loop (Exit-Controlled)
Condition CheckedBefore executing the loop bodyAfter executing the loop body
Minimum Executions0 times (if condition is initially false)1 time (always runs at least once)
Trailing SemicolonNo semicolon after while (cond)Mandatory semicolon: do { ... } while (cond);
Best Use CaseSentinel/EOF reading where input might be emptyInteractive menus where prompt must appear at least once

5.4.4 Nested loop

A nested loop places one loop completely inside the body of another loop. For each single iteration of the outer loop, the inner loop runs through all of its iterations from start to finish (for example, printing 2D patterns, multiplying matrices, or generating multiplication tables). If the outer loop runs M times and the inner loop runs N times, the innermost body executes M * N times.


5.5 Loop interruption

C provides break and continue to alter normal loop flow early based on runtime conditions.

5.5.1 break

The break; statement immediately terminates the innermost enclosing loop (for, while, do-while) or switch statement, transferring control to the first statement after that block.

5.5.2 continue

The continue; statement skips the remaining statements in the current iteration of the innermost loop and jumps directly to the next iteration:

Aspectbreakcontinue
Effect on LoopExits the enclosing loop completelySkips rest of current iteration and starts next iteration
Usable in switch?Yes (exits the switch block)No (only applies to enclosing loops)
Control DestinationStatement immediately after the loopNext iteration check (update in for; condition in while/do-while)

Worked Examples

Example 1

1 (6 marks)

Write a C program using a while loop to compute the sum of digits and the reverse of a positive integer, and trace the loop variables step by step for n = 4729.

C Program Using while Loop:

Sum of Digits and Reverse of a NumberC
#include <stdio.h>

int main(void) {
    int n = 4729, sum = 0, rev = 0;
    while (n > 0) {
        int digit = n % 10;
        sum += digit;
        rev = rev * 10 + digit;
        n /= 10;
    }
    printf("sum=%d rev=%d\n", sum, rev);
    return 0;
}
Iteration Trace for n = 4729
Iterationn (entry)digit = n % 10sumrev = rev * 10 + digitn /= 10
14729999472
24722119247
3477189274
4442292740
Exit0(n > 0 false)229274—
Answer:

Output: sum=22 rev=9274.

Example 2

2 (6 marks)

Trace the exact output of the following C program demonstrating break, continue, and switch fall-through:

Loop Interruption and switch TraceC
#include <stdio.h>

int main(void) {
    int total = 0;
    for (int i = 1; i <= 7; i++) {
        if (i % 3 == 0) {
            continue;
        }
        if (i == 6) {
            break;
        }
        total += i;
    }
    switch (total % 4) {
        case 0: total += 1;
        case 1: total += 2; break;
        default: total += 5;
    }
    printf("total=%d\n", total);
    return 0;
}

Tracing the for Loop:

  • i = 1: 1 % 3 != 0, 1 != 6 -> total = 1
  • i = 2: 2 % 3 != 0, 2 != 6 -> total = 1 + 2 = 3
  • i = 3: 3 % 3 == 0 -> continue skips total += i (total = 3)
  • i = 4: adds 4 -> total = 3 + 4 = 7
  • i = 5: adds 5 -> total = 7 + 5 = 12
  • i = 6: 6 % 3 == 0 hits continue before if (i == 6)! So break is never triggered at i = 6.
  • i = 7: adds 7 -> total = 12 + 7 = 19.
  • Loop ends when i becomes 8.

Tracing the switch Statement: total is 19, so total % 4 = 19 % 4 = 3. Neither case 0: nor case 1: matches 3, so control jumps to default:, executing total += 5 -> 19 + 5 = 24.

Answer:

Output: total=24 (note that i = 6 hit if (i % 3 == 0) continue; before reaching if (i == 6) break;).

Example 3

3 (5 marks)

Write a C program using nested for loops to print a right-angled triangle of numbers with 4 rows (1, 1 2, 1 2 3, 1 2 3 4) and state how many times the inner printf executes.

Designing Outer and Inner Loops:

  • Outer loop r runs from 1 to 4 (controls the row number).
  • Inner loop c runs from 1 to r (prints numbers 1 through r on row r).
  • After the inner loop finishes each row, printf("\n"); starts the next line.
Right-Angled Number TriangleC
#include <stdio.h>

int main(void) {
    for (int r = 1; r <= 4; r++) {
        for (int c = 1; c <= r; c++) {
            printf("%d ", c);
        }
        printf("\n");
    }
    return 0;
}

Counting Inner Executions: Row 1 runs 1 time, row 2 runs 2 times, row 3 runs 3 times, row 4 runs 4 times: 1 + 2 + 3 + 4 = 10 times.

Answer:

Output:

Triangle OutputText
1 
1 2 
1 2 3 
1 2 3 4 

The inner printf("%d ", c); executes 10 times.


Exercises

Exercises — Control Structures

Question 1

Compare the else-if ladder and the switch statement. List three constraints on switch expressions and case labels in C, and explain what happens when break; is omitted from a case.

Comparison and switch Constraints: An else-if ladder evaluates arbitrary Boolean expressions, ranges, and floating-point comparisons sequentially, whereas switch dispatches on discrete constant matches. Three constraints on switch in C:

  1. The switch expression must have an integral type (int, char, enum); float, double, and strings are illegal.
  2. Each case label must be a unique compile-time integer constant expression (variables like case x: are not allowed).
  3. Duplicate case values in the same switch cause a compile-time error.

Effect of Omitting break;: If break; is omitted at the end of a case, execution falls through into the next case (and subsequent cases) unconditionally until a break;, return, or closing brace } is reached.

Answer:

else-if handles ranges and any boolean condition, while switch handles discrete integral constant matches (int/char expression, constant unique case labels). Omitting break; causes fall-through into following case statements.

Question 2

Differentiate between entry-controlled (while, for) and exit-controlled (do-while) loops. Give one scenario where do-while is strictly preferable over while.

Entry-Controlled vs. Exit-Controlled:

  • In while and for, the test condition is evaluated before entering the loop body; if false initially, the body runs 0 times.
  • In do-while, the loop body executes first and the condition is evaluated at the bottom; thus the body always executes at least once.

Practical Scenario for do-while: Menu-driven interactive programs or input-validation prompts (such as prompting a user to enter a choice 1–4 and repeating until a valid number is entered) naturally use do-while because the prompt must appear at least once before validation.

Answer:

Entry-controlled loops (while, for) test before executing (0+ runs), whereas exit-controlled do-while tests after executing (1+ runs). do-while is ideal for menu prompts or input validation that must run at least once.

Question 3

Trace the final value of s printed by this C snippet: int s = 0; for (int k = 1; k <= 20; k++) { if (k % 2 != 0) continue; s += k; } printf("%d\n", s);

Analyzing the continue Condition: k iterates from 1 through 20. Whenever k is odd (k % 2 != 0), continue; skips s += k;, jumps to k++, and tests k <= 20. Whenever k is even, s += k; adds k to s.

Summing the Even Numbers from 2 to 20: s = 2 + 4 + 6 + 8 + 10 + 12 + 14 + 16 + 18 + 20. Pairing terms (2 + 20 = 22, 5 pairs): 5 * 22 = 110.

Answer:

The snippet prints 110 (the sum of even integers from 2 to 20).

Question 4

Explain nested loops and trace the output and inner-loop execution count of: for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 3; j++) { if (i == j) printf("* "); else printf("0 "); } printf("\n"); }

Tracing Each Outer Row (i = 1..4) and Inner Column (j = 1..3):

  • i = 1: j=1 (*), j=2 (0), j=3 (0) -> * 0 0
  • i = 2: j=1 (0), j=2 (*), j=3 (0) -> 0 * 0
  • i = 3: j=1 (0), j=2 (0), j=3 (*) -> 0 0 *
  • i = 4: j=1 (0), j=2 (0), j=3 (0) -> 0 0 0

Total inner iterations = 4 * 3 = 12.

Answer:

Output is a 4x3 grid with * on the main diagonal (* 0 0, 0 * 0, 0 0 *, 0 0 0), and the inner loop executes 12 times.

Question 5

What is the goto statement in C? State its syntax and explain why structured programming discourages its routine use.

Syntax and Behavior of goto: goto label_name; transfers control unconditionally to the statement marked label_name: inside the same function.

Why Routine Use is Discouraged: Unconstrained jumps bypass loop and conditional structures, making control flow difficult to follow ("spaghetti code"), complicating variable initialization/resource tracking, and hindering debugging and maintenance. Standard loops, break, continue, and functions handle almost every case more cleanly.

Answer:

goto label; jumps unconditionally to label: within the same function. It is discouraged because arbitrary jumps obscure program flow and hinder maintainability; structured constructs (if, loops, break, continue) are preferred except for rare multi-loop error cleanup.

← Input and OutputArray and Pointer →