1. Gyanastra
  2. Programming Languages
  3. Programming in C
  4. Control Flow and Sequence Control
Free lesson, no account needed 13 min read 10 practice questions after it
Asked in past papers20 times
  • GATE CSE2025202420192018
  • ISRO2018201720152014201320112008
  • UGC NET202220192015201420132010200820072006

Programming Languages · Programming in C

Control Flow and Sequence Control

Overview

Control flow is the order in which statements execute. In C, sequence is the default: statements run one after another.
Selection statements (if, switch) choose a path; iteration statements (for, while, do-while) repeat a block; jump statements (break, continue, goto, return) transfer control.
UGC NET tests this topic through output-prediction, valid switch cases, loop counts, infinite loops, short-circuit evaluation, and jump-statement matching.
Before studying it, know variables, constants, arithmetic/relational/logical operators, and basic C syntax.

Key concepts

  • Sequence: statements execute in written order unless a control statement changes it.
  • Truth value in C: a condition is true iff its value is nonzero; false iff zero. Relational and logical operators produce int 0 or 1. Thus while (87) is an infinite loop; while (0) never runs.
  • Selection: if (expr) stmt; if (expr) stmt1 else stmt2. The else binds to the nearest unmatched if.
  • switch: switch (expr) { case const1: ...; break; ... default: ... }. expr must have integer type (int, char, enum). Each case label must be an integer constant expression, not a variable, range, or function call. Duplicate case labels are illegal. default is optional.
  • Fall-through: after a matching case, execution continues into following cases until break or the end of the switch. Missing break is the common trap.
  • for: for (init; condition; update) body. init once; condition before each body; body; update; repeat. Omitted condition means true: for(;;) is infinite.
  • while: while (condition) body tests the condition before each iteration; body may run zero times.
  • do-while: do body while (condition); body runs once, then the condition is tested; body runs at least once.
  • break: exits the innermost loop or switch only. In nested loops it does not exit outer loops.
  • continue: skips the rest of the current iteration of the innermost loop and proceeds to the next iteration.
    In a for loop, the update expression runs before the next condition test; in while/do-while, control goes to the condition test.
  • goto: goto label; transfers to label: in the same function. It cannot jump into another function.
  • return: exits the current function; it may return a value.
  • Short-circuit evaluation: A && B evaluates B only if A is true; A || B evaluates B only if A is false. This matters with side effects such as a++ && b++.
  • Operator precedence groups: postfix ++ --, unary ! ++ -- + -, multiplicative * / %, additive + -, relational < <= > >=, equality == !=, bitwise AND &, XOR ^, bitwise OR |, logical AND &&, logical OR ||, conditional ?:, assignment = += -= ..., comma.
    Most binary operators associate left-to-right; assignment and unary associate right-to-left. Precedence determines grouping, not always evaluation order; &&, ||, ?:, and comma impose left-to-right evaluation.
  • Integer division: if both operands are integers, / truncates toward zero. 1/2 is 0; 13/4 is 3; 9/5 is 1. Thus r = 9/5 assigns 1.0 to a float.
  • Post-increment vs pre-increment: i++ yields the old value then increments; ++i increments then yields the new value. For x = 128, 1 + x++ uses 128, so it evaluates to 129.
  • Compound assignment: X -= Y + 1 means X = X - (Y + 1), not X = X - Y + 1.
  • Loop invariant: a property true before and after every iteration. At loop exit, combine the invariant with the exit condition to prove the result.
  • Condition replacement: num != 65 is the same as num > 65 || num < 65 and as !(num == 65). In a condition context, num - 65 also works because it is nonzero exactly when num != 65. But !(num - 65) is the opposite: true when num == 65.

How it works

  1. Sequence and expression evaluation: execute statements top to bottom. Parse expressions by precedence and associativity, then apply short-circuit rules.
    For example, with x = 0.5, j = 1, k = -1, the expression x*3 && 3 || j|k parses as ((x*3) && 3) || (j|k). x*3 is 1.5, which is nonzero, so ((x*3) && 3) is true; || then short-circuits and gives 1. Similarly, x*y < i+j || k with x=0.5, y=0, i=0, j=1, k=-1 becomes 0 < 1 || -1, which is true, so the result is 1.
  2. if/else: evaluate the condition; nonzero is true. if (x = 5) assigns 5 to x and tests 5, so the branch is taken unless the assigned value is 0. if (x == 5) compares.
  3. switch execution: evaluate the controlling integer expression once; compare it with each case label; jump to the matching label; execute from there downward. break exits the switch.
    If no case matches and there is no default, nothing inside the switch executes.
  4. Loop counting: for for (i = a; i <= b; i += s) with s > 0, the number of iterations is floor((b-a)/s)+1 when a <= b, otherwise 0. Nested independent loops multiply their counts.
    A condition such as (i+j+k)%3 == 0 over complete ranges selects exactly one third of the total iterations; for three loops each running 1..30, the total is 27000, so such a condition is true 9000 times.
    For i=1; i<=100; i=i+2, the values are 1,3,...,99; using i<=101 would also print 101, which is not less than 100.
  5. while and do-while: while tests first, so it may run zero times. do-while tests after, so it runs at least once. With num=0, do { --num; printf("%d", num); num++; } while (num >= 0); changes 0 to -1 and back to 0 every iteration, so the condition stays true and the loop is infinite.
    A loop while (digit <= 9) { ++count; ++digit; } with digit=0 runs 10 times because digit takes 0..9; if count starts at 1 and is pre-incremented, it prints 2 through 11.
  6. Jump statements: break leaves only the innermost loop or switch. In while (x <= 10) for (;;) if (++x % 10 == 0) break;, the break leaves only the inner for.
    Starting at x=0, the inner loop raises x to 10 and breaks; the outer while repeats; the inner loop raises x to 20 and breaks; then x <= 10 fails.
    Final x=20. continue skips the rest of the current iteration. goto jumps to a label in the same function. return exits the function.
  7. Recursion: a function calls itself with a smaller argument until a base case. Each call has its own automatic variables on the stack. For sum(n) = n + sum(n-1) with sum(0)=0, sum(5)=5+4+3+2+1+0=15. For f(n)=n+f(n-2) with f(0)=0, f(100)=100+98+...+2+0=2550.
  8. Loop invariant: prove it true before the loop, preserve it through one iteration, then use it at exit. In exponentiation by squaring, maintain m * x^k = p^n and k >= 0. The loop halves k, squares x, and multiplies m when k is odd.
    At exit k=0, so m * x^0 = m = p^n.
Figure. Notice the condition is checked before the body; a yes path executes the body and update, then returns to the condition, while a no path goes to End.

Formulas

  • Truth rule: a condition is true iff its value ≠0\ne 0.
  • Integer division for integers a,ba,b with b≠0b\ne 0: a/ba/b truncates toward zero, and a=(a/b)b+a%ba = (a/b)b + a\%b; the remainder has the sign of the dividend in C99 and later.
  • Loop count for for (i=a; i<=b; i+=s), s>0s>0: N=max⁡(0,⌊(b−a)/s⌋+1)N=\max(0,\lfloor (b-a)/s \rfloor+1).
  • Nested independent loops: total iterations =N1N2⋯Nk= N_1 N_2 \cdots N_k.
  • Sum 1+2+⋯+n=n(n+1)21+2+\cdots+n = \dfrac{n(n+1)}{2}.
  • Compound assignment: X−=Y+1≡X=X−(Y+1)X -= Y+1 \equiv X = X-(Y+1).
  • Exponentiation loop invariant: mxk=pnm x^k = p^n; at exit k=0k=0, hence m=pnm=p^n.

Worked examples

Example 1 — switch fall-through.

#include <stdio.h>
int main(void) {
    int x = 2;
    switch (x) {
        case 1: printf("A");
        case 2: printf("B");
        case 3: printf("C"); break;
        default: printf("D");
    }
    return 0;
}

x=2 matches case 2, so B is printed. There is no break after B, so execution falls into case 3 and prints C. The break then exits the switch. Output: BC.

Example 2 — short-circuit and post-increment.

#include <stdio.h>
int main(void) {
    int a = 0, b = 0;
    if (a++ && b++) { }
    printf("%d %d", a, b);
    return 0;
}

a++ yields old value 0, which is false, so && short-circuits and b++ is not evaluated. a becomes 1; b stays 0. Output: 1 0.

Example 3 — nested loops with break.

#include <stdio.h>
int main(void) {
    int i, j, x = 0;
    for (i = 0; i < 5; ++i)
        for (j = 0; j < i; ++j) {
            x += (i + j - 1);
            break;
        }
    printf("%d", x);
    return 0;
}

The inner break is unconditional, so only j=0 is used whenever the inner loop runs.

iinner runs?value addedx after
0no—0
1yes, j=01+0-1=00
2yes, j=02+0-1=11
3yes, j=03+0-1=23
4yes, j=04+0-1=36

Output: 6.

Example 4 — loop invariant for exponentiation.
Take p=3, n=5, so p^n = 243. Initialise x=3, k=5, m=1; invariant m*x^k = 243 holds because 1*3^5 = 243.

stepkk odd?actionmxinvariant check
start5——131*3^5=243
15yesm=m*x, x=x*x, k=2393*9^2=243
22nox=x*x, k=13813*81^1=243
31yesm=m*x, x=x*x, k=02436561243*1=243

At exit k=0, so m*x^0 = m = p^n. Hence m = p^n.

Example 5 — match jump statements.
List I: return, goto, break, continue.
List II: (i) transfers to a labelled statement in the same function; (ii) exits the current function and may return a value; (iii) exits the innermost loop or switch; (iv) skips the rest of the current iteration and continues with the next.
Correct match: return–(ii), goto–(i), break–(iii), continue–(iv).

Comparison

StatementEffectScopeCommon trap
breakexits innermost loop or switchnearest enclosing loop/switchdoes not exit outer loops
continueskips rest of current iterationinnermost loopin for, update still runs
gotojumps to a labelsame function onlycannot jump to another function
returnexits functionwhole functionmay return a value
LoopCondition testedMinimum runsBest use
whilebefore body0unknown count, may be zero
do-whileafter body1body must run at least once
forbefore body, with init/update0count-controlled loops
Featureifswitch
Condition typeany scalar expressioninteger expression
Labelsnoneinteger constant expressions
Matchingtrue/falseequality with case constants
Fall-throughnoyes, unless break
PairDifference
= vs === assigns; == compares
&& vs &&& is logical and short-circuits; & is bitwise and does not
i++ vs ++ii++ yields old value; ++i yields new value
break vs continuebreak leaves loop/switch; continue starts next iteration

Revision summary

  • Zero is false; every nonzero value is true.
  • Missing break causes fall-through in switch.
  • case labels must be integer constants; ranges and variables are illegal.
  • break exits only the innermost loop or switch.
  • continue skips the rest of the current iteration.
  • do-while runs at least once; while may run zero times.
  • for(;;), while(1), and while(87) are infinite loops.
  • Integer division truncates: 1/2 is 0, which can freeze a loop.
  • && and || short-circuit; side effects may not happen.
  • if (x = 5) assigns and tests 5, usually always true; use ==.
  • Precedence: * / % before + -; && before ||; assignment is low.
  • In nested loops, total iterations multiply; break/continue affect the innermost loop only.

Previous-year exam insights

  • Output-prediction is common: trace switch fall-through, loops, nested break, do-while, post-increment, and short-circuit expressions.
    Check the condition’s truth value and side effects first.
  • Valid switch cases: case labels must be integer constant expressions. case 'A' = printf(...) is invalid, and case 'A' <= x <= 'C' is invalid because it uses a variable/range.
    The valid pattern is separate constant cases with break.
  • Match-the-list asks jump statements: return carries a value, goto needs a label, break exits the innermost loop, continue moves to the next iteration.
  • Infinite-loop recognition: nonzero constant conditions, missing updates, integer division making the update zero, and do-while conditions that stay true.
  • Expression evaluation: use precedence and associativity, then short-circuit.
    Watch integer division, bitwise-vs-logical operators, and pre/post-increment.
  • Loop counting: multiply nested loop counts; conditions such as (i+j+k)%3==0 select one third of complete residue ranges.
  • Loop invariants: prove initial truth, preservation, and use at exit; for exponentiation, k=0 gives m=p^n.
  • Statement-type traps: while vs do-while, break vs continue, = vs ==, and goto label scope.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  1. Predict the output of a switch with and without break and default.
  2. Identify valid and invalid case labels.
  3. Trace for, while, and do-while loops and count their iterations.
  4. Detect infinite loops caused by nonzero constants, missing updates, or integer division.
  5. Apply break and continue correctly in nested loops.
  6. Evaluate expressions using precedence, associativity, short-circuiting, integer division, and pre/post-increment.
  7. Match return, goto, break, and continue to their effects.
  8. Prove a simple loop invariant and use it at loop exit.
  9. Distinguish = from ==, && from &, and while from do-while.
  10. Explain why a goto cannot jump to a label in another function.

Attempt the sub-topic test first, then the subject test.

Pages 1–2 of 2