Computer Science and IT‹›⌂ 0:00 studied

Module 4 · 14 min read · Free chapter

Control flow, functions and recursion

In short

A switch falls through every later case until a break. do-while runs at least once. C passes arguments by value, so a plain swap fails. A static local is initialised once and keeps its value between calls. In recursion, prints before the call come out in call order and prints after it in reverse.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: the reservation counter

Picture a railway reservation counter on a busy morning. The clerk takes a form and checks whether a seat is free; if it is, she books it, and if not, she offers the waiting list. Then she calls "next!" and repeats the same steps until the queue is empty.

Sometimes she cannot answer alone. She asks the chart clerk at the next window, waits for the reply and continues with her own work. That helper does one fixed job and hands back a result.

These three habits are the whole of this chapter. Decisions are if and switch, repetition is a loop, and asking a helper is a function call. A helper who, to finish his job, asks a smaller copy of himself is recursion.

Why it matters. Every algorithm you will study is built from these pieces. GATE tests them through output questions, where one missing break or one static variable changes the whole answer.

if, else and switch with fall-through

In C a condition is just an expression: any non-zero value counts as true and 0 counts as false. So if (n = 0) is legal but wrong, because it assigns 0 to n and then tests 0, which is false. Our test printed "nonzero 0", and gcc with -Wall suggested parentheses around the assignment.

When if statements are nested without braces, the dangling-else rule applies: an else pairs with the nearest earlier unmatched if, whatever the indentation says.

int a = 0, b = 5;
if (a > 1)
    if (b > 1) printf("A\n");
else printf("B\n");          /* belongs to if (b > 1) */
printf("end\n");             /* only "end" is printed */

The indentation suggests that B prints when a is not greater than 1. But the else belongs to the inner if, and since the outer test fails, neither A nor B prints.

A switch compares an integer value with case labels, which must be distinct integer constant expressions. It jumps to the matching label and then falls through every later label until it meets a break or the closing brace. default may be placed anywhere, and it runs only when no case matches.

int x = 2;
switch (x) {
    case 1: printf("one ");
    case 2: printf("two ");
    case 3: printf("three ");
    default: printf("other ");
    case 4: printf("four\n");
}                            /* prints: two three other four */

Why it matters. Fall-through is useful when several cases share code, but a forgotten break is one of the most common bugs. GATE questions almost always hide a missing break or a default placed in the middle.

Loops, break and continue

C has three loops. while (cond) and for (init; cond; update) test the condition before each pass, so their body may run zero times. do { ... } while (cond); tests after the body, so its body always runs at least once.

int i = 10;
do { printf("%d ", i); i++; } while (i < 5);   /* prints 10 once */
int y = 0;
while (y++ < 3);             /* empty body; y ends at 4 */
int j;
for (j = 0; j < 5; j++);     /* stray semicolon: empty body */
printf("%d %d\n", y, j);     /* prints 4 5 */

Trace while (y++ < 3) with care. The tests compare 0, 1, 2 and 3 with 3, and each test also increments y, so the loop stops after the fourth test with y equal to 4. The stray semicolon after the for makes the loop body empty, so j simply climbs to 5.

break leaves the innermost loop or switch at once. continue skips the rest of the current pass; in a for loop, control goes to the update part and then to the test.

int count = 0;
for (int k = 1; k <= 20; k++) {
    if (k % 3 == 0) continue;    /* skip 3, 6, 9 */
    if (k > 10) break;           /* stop at 11 */
    count++;
}
printf("%d\n", count);       /* prints 7 */

Here k runs from 1 to 10, the multiples of 3 are skipped, and the loop breaks at 11. That leaves 1, 2, 4, 5, 7, 8 and 10, so count is 7.

A loop like for (i = 0; i < n; i += 3) runs ⌈n3⌉\lceil \dfrac{n}{3} \rceil times, which is 4 for n=10n = 10. Counting passes like this is the bridge to time complexity.

Why it matters. Off-by-one errors and stray semicolons cause loops that run once too often or never. Exam questions test exactly these edges, so always trace the first and the last pass.

Functions and call by value

A function packages a job under a name. Its prototype, such as int add(int, int);, tells the compiler the return type and parameter types before the first call, and its definition gives the body. The values in a call are arguments, and the names that receive them are parameters.

C passes every argument by value. The function receives a fresh copy, so changing a parameter never changes the caller's variable. That is why the classic swap fails.

void swap(int a, int b) { int t = a; a = b; b = t; }
int p = 1, q = 2;
swap(p, q);
printf("%d %d\n", p, q);     /* prints 1 2: only copies were swapped */

To see why, look at the call stack. Each call pushes an activation record, or stack frame, holding the parameters, local variables and the return address. When swap returns, its frame, with the swapped copies, is simply thrown away.

The fix is to pass the addresses of p and q and swap through pointers. That is still call by value, because the addresses themselves are copied, but it lets the function reach the caller's memory. The full method is taught with pointers in arrays, strings and pointers.

Why it matters. Functions let large programs be built and tested piece by piece. Understanding stack frames also explains recursion, local variables and why returning the address of a local is a serious bug.

Storage classes, scope and lifetime

Every variable has two separate properties. Scope is the part of the program where its name is visible, and lifetime is how long its storage exists. A storage class sets both.

Storage class Where it lives Default value Lifetime
auto stack garbage (indeterminate) until the block ends
register a register if possible garbage (indeterminate) until the block ends
static data area 0 whole program
extern data area, defined elsewhere 0 at its definition whole program

A static local variable is initialised once, before the program starts, and it keeps its value between calls. An auto local is created fresh on every call. These lines show the difference.

int counter(void) { static int c = 0; c++; return c; }
int g(void) { int c = 0; c++; return c; }
counter(); counter();
printf("%d\n", counter());   /* prints 3 */
printf("%d %d\n", g(), g()); /* prints 1 1 */

A register variable is only a request for fast storage, and the compiler may ignore it. But you can never take its address: gcc rejected &r with "address of register variable 'r' requested". An extern declaration says "this variable is defined in another file"; we compiled two files in which one defined int total and the other declared extern int total, and the sum printed was 12.

Scope follows the braces. A name declared inside a block hides an outer name of the same spelling until the block ends. With a global x = 10, a local x = 20 in main and an inner block with x = 30, a function that prints x sees the global, so the output was "10 30 20".

static on a global variable or a function means something else. It gives internal linkage, so the name is private to its own file and other files cannot reach it with extern.

Why it matters. Static variables hold state such as counters and caches without exposing a global. In GATE, a static variable inside a function or a recursion is the most common twist in output questions.

Recursion and how to trace it

A function is recursive when it calls itself on a smaller input. It needs two parts: a base case that answers directly, and a recursive case that moves towards the base case. Factorial is the standard first example.

int fact(int n) {
    if (n <= 1) return 1;            /* base case */
    return n * fact(n - 1);          /* recursive case */
}                                    /* fact(5) returned 120 */

Each call gets its own stack frame with its own n. For fact(4), frames for 4, 3, 2 and 1 pile up; then fact(1) returns 1, and the answers flow back as 2, 6 and 24. If the base case is missing or never reached, frames pile up until the stack runs out, which is a stack overflow.

The key to tracing output is where the print sits. Code before the recursive call runs on the way down, in call order. Code after the call runs on the way back up, in reverse order.

void down(int n) { if (n == 0) return; printf("%d ", n); down(n - 1); }
void up(int n)   { if (n == 0) return; up(n - 1); printf("%d ", n); }
void both(int n) { if (n == 0) return; printf("%d ", n); both(n - 1); printf("%d ", n); }
/* down(3): 3 2 1    up(3): 1 2 3    both(3): 3 2 1 1 2 3 */

When a function makes two recursive calls, draw a tree instead of a stack. For fun(n) that does fun(n - 1), prints n and does fun(n - 1) again, fun(3) printed "1 2 1 3 1 2 1". The number of values printed obeys P(n)=2P(n−1)+1P(n) = 2P(n - 1) + 1, which gives 2n−12^n - 1, so 7 for n=3n = 3.

Why it matters. Recursion expresses tree walks, divide and conquer and backtracking in a few lines. Tracing it by hand, frame by frame, is a skill GATE tests almost every year.

GATE-style traces: call counts, statics and tail recursion

Counting calls. The naive Fibonacci function returns n for n≤1n \le 1 and otherwise fib(n - 1) + fib(n - 2). If C(n)C(n) is the number of calls for fib(n), then C(n)=C(n−1)+C(n−2)+1C(n) = C(n - 1) + C(n - 2) + 1 with C(0)=C(1)=1C(0) = C(1) = 1. This solves to

C(n)=2F(n+1)−1C(n) = 2F(n + 1) - 1

where F is the Fibonacci sequence. With a global counter we measured 15 calls for fib(5) and 25 for fib(6), which matches 2×8−12 \times 8 - 1 and 2×13−12 \times 13 - 1. The same subproblems are solved again and again, so the time is exponential.

A static inside recursion. A static variable is shared by all calls, and it survives after the outermost call returns. This trips many students.

int sum(int n) {
    static int s = 0;
    if (n == 0) return s;
    s += n;
    return sum(n - 1);
}
printf("%d\n", sum(4));      /* prints 10 */
printf("%d\n", sum(2));      /* prints 13, not 3 */

The first call adds 4, 3, 2 and 1 into s, giving 10. The second call starts with s still 10 and adds 2 and 1, giving 13.

A recurrence for the return value. For r(n) returning 1 when n≤0n \le 0 and otherwise r(n - 1) + r(n - 2) + 1, build a table from the bottom: r(1) is 3, r(2) is 5 and r(3) is 9. Our run printed 9, which confirms the table, and the table method is faster than drawing the whole tree.

Tail recursion. A call is a tail call when it is the very last action, with nothing left to do after it returns. In n * fact(n - 1) the multiplication still waits, so it is not a tail call. Passing an accumulator fixes that.

int fact_acc(int n, int acc) {
    if (n <= 1) return acc;
    return fact_acc(n - 1, n * acc);    /* tail call */
}                                       /* fact_acc(5, 1) returned 120 */

A tail-recursive function can be rewritten as a loop that updates n and acc, using constant stack space. The C standard does not require compilers to make this change, so do not assume it happens.

Why it matters. Call counts reveal why some recursive programs crawl, and they lead straight to memoisation and dynamic programming. Tail recursion shows how to keep the elegance of recursion without its stack cost.

Descriptive lens: how written papers ask this

Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about this topic in four ways.

  1. They ask you to compare loops, or break and continue, with flow charts and small examples.
  2. They ask you to explain call by value, often by showing why a swap function fails.
  3. They ask you to tabulate the storage classes by storage, default value, scope and lifetime.
  4. They ask you to write and trace a recursive function, such as factorial, Fibonacci or the sum of digits, and to compare it with an iterative version.

Practice questions (our own, not previous-year questions).

  1. Differentiate between while and do-while loops with an example in which their outputs differ. (5 marks)
  2. Explain the four storage classes of C with their scope, lifetime and default values, and write a program that shows the effect of a static local variable. (10 marks)
  3. What is recursion? Write a recursive function for the nth Fibonacci number, trace the calls for n=4n = 4, and explain why it is slow. (15 marks)

Answer plan for question 3.

  • Define recursion as a function calling itself on a smaller input, and name the base case and the recursive case.
  • Write the function that returns n for n≤1n \le 1 and otherwise returns fib(n - 1) + fib(n - 2).
  • Draw the recursion tree for fib(4) and show that it makes 9 calls and returns 3.
  • Point out that fib(2) is computed twice and fib(1) three times, so work is repeated.
  • State that the number of calls is 2F(n+1)−12F(n + 1) - 1, which grows exponentially with n.
  • Suggest an iterative loop or a memo table that stores each answer once, which brings the time down to O(n)O(n).

Quick revision

  • Non-zero is true and 0 is false, and an else pairs with the nearest unmatched if.
  • A switch falls through every later label until a break, and case labels must be integer constants.
  • while and for may run zero times, while do-while always runs at least once.
  • break leaves the innermost loop or switch, and continue skips to the next test or update.
  • C passes arguments by value, so a swap on plain parameters changes only the copies.
  • Each call gets a stack frame with parameters, locals and the return address.
  • static locals are initialised once, default to 0 and keep their value between calls.
  • A register variable has no address, and extern declares a variable defined elsewhere.
  • Prints before a recursive call come out in call order, and prints after it come out in reverse.
  • Naive fib(n) makes 2F(n+1)−12F(n + 1) - 1 calls, which is 15 for fib(5).
  • A tail call is the last action of a function and can be turned into a loop.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. `int n = 0; if (n = 0) printf("zero"); else printf("nonzero");` prints:

  2. `int a = 0, b = 5; if (a > 1) if (b > 1) printf("A"); else printf("B");` prints:

  3. With x = 2, `switch (x) { case 1: printf("one "); case 2: printf("two "); case 3: printf("three "); default: printf("other "); case 4: printf("four"); }` prints:

  4. `int i = 10; do { printf("%d ", i); i++; } while (i < 5);` prints:

  5. After `int y = 0; while (y++ < 3);` the value of y is:

  6. `for (k = 1; k <= 20; k++) { if (k % 3 == 0) continue; if (k > 10) break; count++; }` with count starting at 0 leaves count equal to:

  7. `void swap(int a, int b) { int t = a; a = b; b = t; }` is called as `swap(p, q)` with p = 1, q = 2. Afterwards p and q are:

  8. An activation record (stack frame) of a C function call does NOT normally hold:

  9. `int f(void) { static int x = 5; return x--; }` and `int a = f(), b = f(), c = f();` give a, b, c as:

  10. Global `int x = 10;`, `void show(void) { printf("%d ", x); }`, and in main: `int x = 20; show(); { int x = 30; printf("%d ", x); } printf("%d", x);`. The output is:

  11. A recursive function whose base case is never reached will most likely:

  12. `void both(int n) { if (n == 0) return; printf("%d ", n); both(n - 1); printf("%d ", n); }` with `both(3)` prints:

  13. `void fun(int n) { if (n > 0) { fun(n - 1); printf("%d ", n); fun(n - 1); } }` with `fun(3)` prints:

  14. The naive recursive fib with fib(0) = 0 and fib(1) = 1 makes how many calls in total for fib(5)?

  15. Which function is tail recursive?

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

What is fall-through in a switch statement?

After jumping to the matching case, control runs into every later case, including default, until it meets a break or the end of the switch.

How is a static local variable different from an auto variable?

A static local is initialised once, defaults to 0 and keeps its value between calls. An auto variable is created fresh on every call.

How many calls does naive recursive fib(5) make?

It makes 15 calls. In general fib(n) makes 2F(n + 1) − 1 calls, which grows exponentially.

What is tail recursion?

A recursive call is a tail call when it is the last action of the function. Such a function can be rewritten as a loop, often with an accumulator.

More in this module: Programming in C

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Problem Solving through Programming in C (IIT Kharagpur, 106105171): control statements, functions, storage classes and recursion