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
int0or1. Thuswhile (87)is an infinite loop;while (0)never runs. - Selection:
if (expr) stmt;if (expr) stmt1 else stmt2. Theelsebinds to the nearest unmatchedif. - switch:
switch (expr) { case const1: ...; break; ... default: ... }.exprmust have integer type (int,char,enum). Eachcaselabel must be an integer constant expression, not a variable, range, or function call. Duplicate case labels are illegal.defaultis optional. - Fall-through: after a matching case, execution continues into following cases until
breakor the end of the switch. Missingbreakis the common trap. - for:
for (init; condition; update) body.initonce; condition before each body; body; update; repeat. Omitted condition means true:for(;;)is infinite. - while:
while (condition) bodytests 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
switchonly. 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 aforloop, the update expression runs before the next condition test; inwhile/do-while, control goes to the condition test. - goto:
goto label;transfers tolabel:in the same function. It cannot jump into another function. - return: exits the current function; it may return a value.
- Short-circuit evaluation:
A && BevaluatesBonly ifAis true;A || BevaluatesBonly ifAis false. This matters with side effects such asa++ && 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/2is0;13/4is3;9/5is1. Thusr = 9/5assigns1.0to afloat. - Post-increment vs pre-increment:
i++yields the old value then increments;++iincrements then yields the new value. Forx = 128,1 + x++uses128, so it evaluates to129. - Compound assignment:
X -= Y + 1meansX = X - (Y + 1), notX = 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 != 65is the same asnum > 65 || num < 65and as!(num == 65). In a condition context,num - 65also works because it is nonzero exactly whennum != 65. But!(num - 65)is the opposite: true whennum == 65.
How it works
- Sequence and expression evaluation: execute statements top to bottom. Parse expressions by precedence and associativity, then apply short-circuit rules.
For example, withx = 0.5,j = 1,k = -1, the expressionx*3 && 3 || j|kparses as((x*3) && 3) || (j|k).x*3is1.5, which is nonzero, so((x*3) && 3)is true;||then short-circuits and gives1. Similarly,x*y < i+j || kwithx=0.5, y=0, i=0, j=1, k=-1becomes0 < 1 || -1, which is true, so the result is1. - if/else: evaluate the condition; nonzero is true.
if (x = 5)assigns5toxand tests5, so the branch is taken unless the assigned value is0.if (x == 5)compares. - switch execution: evaluate the controlling integer expression once; compare it with each case label; jump to the matching label; execute from there downward.
breakexits the switch.
If no case matches and there is nodefault, nothing inside the switch executes. - Loop counting: for
for (i = a; i <= b; i += s)withs > 0, the number of iterations isfloor((b-a)/s)+1whena <= b, otherwise0. Nested independent loops multiply their counts.
A condition such as(i+j+k)%3 == 0over complete ranges selects exactly one third of the total iterations; for three loops each running1..30, the total is27000, so such a condition is true9000times.
Fori=1; i<=100; i=i+2, the values are1,3,...,99; usingi<=101would also print101, which is not less than100. - while and do-while:
whiletests first, so it may run zero times.do-whiletests after, so it runs at least once. Withnum=0,do { --num; printf("%d", num); num++; } while (num >= 0);changes0to-1and back to0every iteration, so the condition stays true and the loop is infinite.
A loopwhile (digit <= 9) { ++count; ++digit; }withdigit=0runs10times becausedigittakes0..9; ifcountstarts at1and is pre-incremented, it prints2through11. - Jump statements:
breakleaves only the innermost loop or switch. Inwhile (x <= 10) for (;;) if (++x % 10 == 0) break;, thebreakleaves only the innerfor.
Starting atx=0, the inner loop raisesxto10and breaks; the outerwhilerepeats; the inner loop raisesxto20and breaks; thenx <= 10fails.
Finalx=20.continueskips the rest of the current iteration.gotojumps to a label in the same function.returnexits the function. - 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)withsum(0)=0,sum(5)=5+4+3+2+1+0=15. Forf(n)=n+f(n-2)withf(0)=0,f(100)=100+98+...+2+0=2550. - 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^nandk >= 0. The loop halvesk, squaresx, and multipliesmwhenkis odd.
At exitk=0, som * x^0 = m = p^n.
Drawing the diagram…
Formulas
- Truth rule: a condition is true iff its value .
- Integer division for integers with : truncates toward zero, and ; the remainder has the sign of the dividend in C99 and later.
- Loop count for
for (i=a; i<=b; i+=s), : . - Nested independent loops: total iterations .
- Sum .
- Compound assignment: .
- Exponentiation loop invariant: ; at exit , hence .
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.
i | inner runs? | value added | x after |
|---|---|---|---|
| 0 | no | — | 0 |
| 1 | yes, j=0 | 1+0-1=0 | 0 |
| 2 | yes, j=0 | 2+0-1=1 | 1 |
| 3 | yes, j=0 | 3+0-1=2 | 3 |
| 4 | yes, j=0 | 4+0-1=3 | 6 |
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.
| step | k | k odd? | action | m | x | invariant check |
|---|---|---|---|---|---|---|
| start | 5 | — | — | 1 | 3 | 1*3^5=243 |
| 1 | 5 | yes | m=m*x, x=x*x, k=2 | 3 | 9 | 3*9^2=243 |
| 2 | 2 | no | x=x*x, k=1 | 3 | 81 | 3*81^1=243 |
| 3 | 1 | yes | m=m*x, x=x*x, k=0 | 243 | 6561 | 243*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
| Statement | Effect | Scope | Common trap |
|---|---|---|---|
break | exits innermost loop or switch | nearest enclosing loop/switch | does not exit outer loops |
continue | skips rest of current iteration | innermost loop | in for, update still runs |
goto | jumps to a label | same function only | cannot jump to another function |
return | exits function | whole function | may return a value |
| Loop | Condition tested | Minimum runs | Best use |
|---|---|---|---|
while | before body | 0 | unknown count, may be zero |
do-while | after body | 1 | body must run at least once |
for | before body, with init/update | 0 | count-controlled loops |
| Feature | if | switch |
|---|---|---|
| Condition type | any scalar expression | integer expression |
| Labels | none | integer constant expressions |
| Matching | true/false | equality with case constants |
| Fall-through | no | yes, unless break |
| Pair | Difference |
|---|---|
= vs == | = assigns; == compares |
&& vs & | && is logical and short-circuits; & is bitwise and does not |
i++ vs ++i | i++ yields old value; ++i yields new value |
break vs continue | break leaves loop/switch; continue starts next iteration |
Revision summary
- Zero is false; every nonzero value is true.
- Missing
breakcauses fall-through inswitch. caselabels must be integer constants; ranges and variables are illegal.breakexits only the innermost loop or switch.continueskips the rest of the current iteration.do-whileruns at least once;whilemay run zero times.for(;;),while(1), andwhile(87)are infinite loops.- Integer division truncates:
1/2is0, which can freeze a loop. &&and||short-circuit; side effects may not happen.if (x = 5)assigns and tests5, usually always true; use==.- Precedence:
* / %before+ -;&&before||; assignment is low. - In nested loops, total iterations multiply;
break/continueaffect the innermost loop only.
Previous-year exam insights
- Output-prediction is common: trace
switchfall-through, loops, nestedbreak,do-while, post-increment, and short-circuit expressions.
Check the condition’s truth value and side effects first. - Valid switch cases:
caselabels must be integer constant expressions.case 'A' = printf(...)is invalid, andcase 'A' <= x <= 'C'is invalid because it uses a variable/range.
The valid pattern is separate constant cases withbreak. - Match-the-list asks jump statements:
returncarries a value,gotoneeds a label,breakexits the innermost loop,continuemoves to the next iteration. - Infinite-loop recognition: nonzero constant conditions, missing updates, integer division making the update zero, and
do-whileconditions 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==0select one third of complete residue ranges. - Loop invariants: prove initial truth, preservation, and use at exit; for exponentiation,
k=0givesm=p^n. - Statement-type traps:
whilevsdo-while,breakvscontinue,=vs==, andgotolabel scope.
Practice at PARIKSHA
You are ready for the PARIKSHA tests of this sub-topic when you can:
- Predict the output of a
switchwith and withoutbreakanddefault. - Identify valid and invalid
caselabels. - Trace
for,while, anddo-whileloops and count their iterations. - Detect infinite loops caused by nonzero constants, missing updates, or integer division.
- Apply
breakandcontinuecorrectly in nested loops. - Evaluate expressions using precedence, associativity, short-circuiting, integer division, and pre/post-increment.
- Match
return,goto,break, andcontinueto their effects. - Prove a simple loop invariant and use it at loop exit.
- Distinguish
=from==,&&from&, andwhilefromdo-while. - Explain why a
gotocannot jump to a label in another function.
Attempt the sub-topic test first, then the subject test.