Karnataka KSEAB SSLC JTS Programming in ANSI C study materials
Karnataka KSEAB SSLC JTS Programming in ANSI C study resources

Karnataka KSEAB SSLC JTS Programming in ANSI C: Control Structures: if, if-else, switch, for, while, do-while, break, continue, goto

Karnataka KSEAB SSLC JTS Programming in ANSI C · Work through your exam, one topic at a time.

All guide sections

Control Structures: if, if-else, switch, for, while, do-while, break, continue, goto

This domain tests selection and iteration: choosing the right construct, knowing which one runs its body at least once, and predicting exactly how many times a loop runs.

Selection

if (expr) treats any non-zero value as true; else binds to the nearest unmatched if. switch (expr) requires an integer or enumeration expression; each case label must be an integer constant expression, and control falls through into the next case unless break or return stops it. default is optional and may appear anywhere, though convention puts it last.

Iteration

for (init; test; update), while (test) and do { } while (test); - the do-while body always runs at least once and needs the trailing semicolon. break leaves the innermost loop or switch; continue skips to the next iteration, and in a for loop the update expression still runs. goto label; jumps within one function and is best reserved for breaking out of deeply nested loops.

Worked example

int sum = 0;
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) continue;
    sum += i;
}

The values added are 1, 3, 5, 7 and 9, so sum is 25. continue skips the even values but i++ still executes, so the loop terminates normally.

Traps

  • while (i <= n); - the stray semicolon creates an empty body and an infinite loop.
  • Omitting break in a switch produces fall-through, a favourite exam question.
  • switch on a float or a string is a compile-time error.
  • for (i = 0; i <= n; i++) runs n+1 times, not n.
  • Without braces, an else may attach to the wrong if.