Control Structures
Open in the Padhaiko app5.1 Introduction to simple and compound statement
In C, programs execute instructions composed of statements.
- Simple (Expression) Statement: A single executable expression terminated by a semicolon
;(for example,sum = a + b;,i++;, orprintf("Done\n");). A lone semicolon;is a null statement that performs no action. - Compound Statement (Block): Zero or more declarations and statements grouped inside curly braces
{ ... }. A compound statement is treated syntactically as a single statement, allowing multiple actions inside anif,else, or loop body, and it creates a local block scope for variables declared inside it.
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.
#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.
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 (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.
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).
| Feature | Rule in C |
|---|---|
| Control Expression | Must evaluate to an integer or character (float/double and strings are invalid) |
| Case Labels | Must be unique compile-time constant expressions (e.g., case 1:, case 'A':) |
Fall-Through & break | Execution falls through into subsequent case blocks unless terminated by break; |
| Default Case | default: runs if no case matches (optional, usually placed last) |
| Aspect | else-if Ladder | switch Statement |
|---|---|---|
| Condition Types | Supports ranges (x >= 50), floats, logical &&/||, and inequalities | Tests equality against integer/char constants only |
| Readability for Menus | Verbose when comparing one variable to 5+ fixed options | Clean, structured multi-way dispatch |
| Execution Transfer | Evaluates conditions sequentially top to bottom | Can 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:
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:
initializationexecutes once before the loop begins.conditionis tested; if false (0), the loop terminates immediately.bodyexecutes.updateexecutes, and control returns to testingcondition.
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 (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);.
| Aspect | while Loop (Entry-Controlled) | do-while Loop (Exit-Controlled) |
|---|---|---|
| Condition Checked | Before executing the loop body | After executing the loop body |
| Minimum Executions | 0 times (if condition is initially false) | 1 time (always runs at least once) |
| Trailing Semicolon | No semicolon after while (cond) | Mandatory semicolon: do { ... } while (cond); |
| Best Use Case | Sentinel/EOF reading where input might be empty | Interactive 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:
- In a
forloop,continue;jumps to the update expression, then re-tests the condition. - In
whileanddo-whileloops,continue;jumps directly to testing the loop condition (so make sure the loop variable is updated beforecontinueto avoid an infinite loop!).
| Aspect | break | continue |
|---|---|---|
| Effect on Loop | Exits the enclosing loop completely | Skips rest of current iteration and starts next iteration |
Usable in switch? | Yes (exits the switch block) | No (only applies to enclosing loops) |
| Control Destination | Statement immediately after the loop | Next iteration check (update in for; condition in while/do-while) |
Worked Examples
1
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:
#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 | n (entry) | digit = n % 10 | sum | rev = rev * 10 + digit | n /= 10 |
|---|---|---|---|---|---|
| 1 | 4729 | 9 | 9 | 9 | 472 |
| 2 | 472 | 2 | 11 | 92 | 47 |
| 3 | 47 | 7 | 18 | 927 | 4 |
| 4 | 4 | 4 | 22 | 9274 | 0 |
| Exit | 0 | (n > 0 false) | 22 | 9274 | — |
Output: sum=22 rev=9274.
2
Trace the exact output of the following C program demonstrating break, continue, and switch fall-through:
#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 = 1i = 2:2 % 3 != 0,2 != 6->total = 1 + 2 = 3i = 3:3 % 3 == 0->continueskipstotal += i(total = 3)i = 4: adds4->total = 3 + 4 = 7i = 5: adds5->total = 7 + 5 = 12i = 6:6 % 3 == 0hitscontinuebeforeif (i == 6)! Sobreakis never triggered ati = 6.i = 7: adds7->total = 12 + 7 = 19.- Loop ends when
ibecomes8.
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.
Output: total=24 (note that i = 6 hit if (i % 3 == 0) continue; before reaching if (i == 6) break;).
3
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
rruns from1to4(controls the row number). - Inner loop
cruns from1tor(prints numbers1throughron rowr). - After the inner loop finishes each row,
printf("\n");starts the next line.
#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.
Output:
1
1 2
1 2 3
1 2 3 4 The inner printf("%d ", c); executes 10 times.
Exercises
Exercises — Control Structures
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:
- The
switchexpression must have an integral type (int,char,enum);float,double, and strings are illegal. - Each
caselabel must be a unique compile-time integer constant expression (variables likecase x:are not allowed). - Duplicate
casevalues in the sameswitchcause 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.
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.
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
whileandfor, the test condition is evaluated before entering the loop body; if false initially, the body runs0times. - 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.
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.
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.
The snippet prints 110 (the sum of even integers from 2 to 20).
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 0i = 2:j=1(0),j=2(*),j=3(0) ->0 * 0i = 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.
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.
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.
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.