Programming & DSA
C Programming
GATE C questions are output-tracing puzzles: master precedence, integer arithmetic, scope, parameter passing, and recursion order, and trace line by line.
GATE CSE C programming — data types, operators, control flow, functions, scope, recursion, call-by-value and the runtime stack, with output-tracing samples and drills.
Learning outcomes
- Evaluate C expressions correctly using operator precedence, integer division, and short-circuit rules
- Trace loops, switch fall-through, and nested control flow without skipping a step
- Explain scope and storage classes (auto, static, extern) and predict static-variable behaviour
- Trace recursion and the runtime stack, and distinguish call-by-value from pointer-based call-by-reference
Data types and operators
- GATE usually assumes char = 1 byte, short = 2, int = 4, long = 4 or 8, float = 4, double = 8 bytes unless the question states otherwise. Always use the sizes given in the stem.
- Integer division truncates toward zero (C99): 7/2 = 3 and -7/2 = -3. The remainder takes the sign of the dividend: -7 % 2 = -1 and 7 % -2 = 1. Always check a/b * b + a%b == a.
- Mixed arithmetic promotes to the wider type: int/int stays an integer even if assigned to a float (float f = 7/2 gives 3.0). Use 7/2.0 to get 3.5.
- Unsigned arithmetic wraps modulo 2^n (unsigned char c = 255; c++ gives 0). Signed overflow is undefined behaviour — GATE avoids it or states wrap-around explicitly.
- = is assignment, == is comparison. An expression like if (x = 0) assigns 0 and is therefore false. Relational chains such as 5 > 3 > 1 evaluate left to right: (5>3)=1, then 1>1 = 0.
- Logical && and || short-circuit: in a && b, b is NOT evaluated when a is 0; in a || b, b is NOT evaluated when a is non-zero. Side effects such as b++ inside the skipped operand never happen.
- Expressions that modify and read the same variable without a sequence point (like i = i++ + ++i) are undefined behaviour; GATE rarely asks them, and the safe answer is usually "compiler dependent".
| Precedence (high → low) | Operators | Associativity |
|---|---|---|
| 1 | () [] -> . postfix ++ -- | Left to right |
| 2 | unary + - ! ~ * & sizeof prefix ++ -- | Right to left |
| 3 | * / % | Left to right |
| 4 | + - | Left to right |
| 5 | < <= > >= then == != | Left to right |
| 6 | && then || | Left to right |
| 7 | ?: then = += -= ... | Right to left |
Worked example
Problem. What does printf("%d", 7/2 + 7%2 + -7/2) print (C99, 32-bit int)?
Solution. 7/2 = 3, 7%2 = 1, (-7)/2 = -3 (unary minus binds tighter). Sum = 3 + 1 − 3 = 1.
Control flow
- if/else: the else belongs to the nearest unmatched if (dangling else). Braces decide structure, indentation does not.
- for (init; cond; update) body: init runs once, cond is checked before every iteration, update runs after the body. A stray semicolon (for(...); ) makes the loop body empty and the next statement runs once after the loop.
- while checks first (may run 0 times); do-while checks after the body (runs at least once).
- break leaves the nearest enclosing loop or switch; continue skips the rest of the body and jumps to the next iteration check (for a for-loop it still runs the update).
- switch jumps to the matching case label and then FALLS THROUGH to later cases until a break or the end. default may appear anywhere; it runs only if no case matches, but fall-through still continues from it.
- Loop count shortcuts: for(i=0;i<n;i++) runs n times; for(i=1;i<=n;i*=2) runs floor(log2 n)+1 times; for(i=n;i>0;i/=2) also runs floor(log2 n)+1 times.
Worked example
Problem. int i, s = 0; for (i = 1; i <= 10; i++) { if (i % 3 == 0) continue; s += i; } What is s?
Solution. Sum of 1..10 = 55; multiples of 3 skipped: 3+6+9 = 18. s = 55 − 18 = 37.
Functions, scope, and storage classes
- C uses lexical (static) scoping: a name refers to the nearest enclosing declaration in the source text, not the caller. Inner-block declarations hide (shadow) outer ones.
- auto (default for locals): lives on the stack, uninitialised (garbage) unless set. Created at block entry, destroyed at exit.
- static local: initialised once (default 0), keeps its value across calls, but visible only inside the function. Lives in the data segment, not the stack.
- Global variables: default-initialised to 0, visible in all functions after the declaration. static at file scope limits visibility to that file. extern declares a variable defined elsewhere.
- register is only a hint (you cannot take its address with &).
- A function needs a prototype or definition before use; returning without a value from a non-void function and using it is undefined.
Formulas to remember
-
static int c = 0; → initialised once, persists across calls -
Global/static default value = 0; auto local default = indeterminate
Worked example
Problem. int f() { static int c = 0; c++; return c; } If f() is called three separate times, what are the returns?
Solution. c persists: the returns are 1, 2, 3 (a plain auto c would return 1 every time).
Parameter passing: value vs pointer
- C passes ALL arguments by value: the callee receives copies of the actual parameters. Changing the formal parameter does not change the caller variable.
- To modify the caller variable you pass its address (a pointer) by value and dereference: void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }. This is often called "call by reference" but it is still pass-by-value of the pointer.
- Passing an array name passes the address of its first element (array decays to a pointer), so the callee can modify the caller array elements.
- A swap(int a, int b) that swaps only the local copies leaves the caller values unchanged — a classic GATE output question.
- Returning a pointer to a local (auto) variable is a bug: the stack frame is gone, so the pointer dangles.
- Argument evaluation order for a call like f(i++, i++) is unspecified — treat such outputs as compiler dependent.
Worked example
Problem. void inc(int x) { x = x + 1; } int a = 5; inc(a); What is a afterwards?
Solution. a stays 5 because x is a copy. With void inc(int *x) { *x = *x + 1; } and inc(&a), a becomes 6.
Recursion and the runtime stack
- Each call pushes an activation record (stack frame) holding the parameters, the return address, saved frame pointer, and local variables. Returning pops it. Recursion depth = number of frames simultaneously on the stack.
- Every recursion needs a base case that stops further calls; a missing or unreachable base case causes stack overflow.
- Statements placed BEFORE the recursive call run in call order (going down); statements AFTER it run in reverse order (while unwinding). f(n){ if(n==0) return; f(n-1); printf(n); } prints 1 2 ... n.
- Space complexity of simple linear recursion is O(depth) because of the stack, even if no extra arrays are used.
- Naive Fibonacci makes exponential calls: calls C(n) = C(n−1) + C(n−2) + 1 with C(0)=C(1)=1 gives 1, 1, 3, 5, 9, 15, ... Many sub-problems are recomputed.
- Tail recursion (recursive call is the last action) can be turned into a loop by an optimiser, but C compilers are not required to do so.
| n | fib calls C(n) | Max depth of stack (frames) |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 1 | 1 |
| 2 | 3 | 2 |
| 3 | 5 | 3 |
| 4 | 9 | 4 |
Worked example
Problem. int g(int n) { if (n <= 0) return 0; return 1 + g(n - 1); } What is g(5) and how many frames of g are active at the deepest point?
Solution. g(5) = 5. Frames: n = 5, 4, 3, 2, 1, 0 → 6 frames of g at the deepest point (excluding main).
GATE exam tricks — C output tracing
- Macros are textual substitution, not function calls: #define SQ(x) x*x makes SQ(2+3) expand to 2+3*2+3 = 11, not 25. Parenthesise mentally before evaluating.
- printf returns the number of characters printed: printf("%d", printf("AB")) first prints AB, then prints 2, so the screen shows AB2.
- Comma operator evaluates left to right and yields the last value: x = (1, 2, 3) gives 3, but x = 1, 2, 3 parses as (x = 1), 2, 3 so x is 1.
- char and short are promoted to int in arithmetic. A signed char holding 200 wraps to -56 on typical machines, and %d of a negative char shows the sign-extended value.
- Ternary ?: is right-associative and lower than ||: a ? b : c ? d : e means a ? b : (c ? d : e).
- For recursion, decide first whether the statement is before or after the recursive call, then write the call tree and read outputs in the correct order (see the figure).
- When two answer options differ only in order (3 2 1 vs 1 2 3), the question is almost always testing before/after the recursive call.
Worked example
Problem. #define SQ(x) x*x What does printf("%d", 100/SQ(5)) print?
Solution. 100/SQ(5) expands to 100/5*5. / and * are left to right: (100/5)*5 = 20*5 = 100, not 4.
Bit tricks and iteration-count shortcuts
- n & (n-1) clears the lowest set bit; looping n = n & (n-1) until 0 counts the set bits (Kernighan). n & -n isolates the lowest set bit.
- x << k multiplies by 2^k and x >> k divides by 2^k (for non-negative values). ~0 is -1 on two's complement machines; ^ with the same value gives 0.
- & and | are bitwise and always evaluate both operands; && and || are logical and short-circuit. Mixing them up is a classic wrong-option trap.
- A loop like for (i = 1; i < n; i = i * 2) runs ceil(log2 n) times; for (i = 1; i <= n; i++) for (j = 1; j <= i; j++) runs n(n+1)/2 times in total.
- Nested loops with an inner bound that depends on the outer variable: write the total as a sum, then use the arithmetic-series formulas.
Worked example
Problem. unsigned n = 40; int c = 0; while (n) { n = n & (n - 1); c++; } What is c?
Solution. 40 = 101000 in binary has two set bits, and each iteration removes the lowest set bit: 101000 -> 100000 -> 0. c = 2.
Exam tips
- Trace with a table: one column per variable, one row per statement or iteration.
- Check integer division, % with negatives, and char/unsigned wrap-around before computing.
- For recursion, draw the call tree and note whether the print is before or after the recursive call.
- static locals and globals keep values across calls; auto locals do not.
- Remember C is pass-by-value; only pointers let the callee change caller data.
10 GATE-style MCQs for C Programming with full explanations. Attempt each question before revealing the answer.
What is the output of printf("%d", 7/2 + 7%2 + -7/2); in C99 with 32-bit int?
Show answer & explanation
Answer: B
7/2 = 3, 7%2 = 1, (-7)/2 = -3 (truncation toward zero). 3 + 1 + (−3) = 1.
int f() { static int c = 0; c++; return c; } If a = f(); b = f(); d = f(); are executed in sequence, what is a + b + d?
Show answer & explanation
Answer: B
The static variable persists: the calls return 1, 2, 3, so the sum is 6.
void inc(int x) { x = x + 1; } int main() { int a = 5; inc(a); printf("%d", a); } prints:
Show answer & explanation
Answer: B
x is a copy of a (call-by-value), so the caller variable a is unchanged and 5 is printed.
void f(int n) { if (n == 0) return; f(n - 1); printf("%d ", n); } What does f(3) print?
Show answer & explanation
Answer: B
The print comes after the recursive call, so output happens while unwinding: f(1) prints 1 first, then 2, then 3.
int fib(int n) { return n < 2 ? n : fib(n-1) + fib(n-2); } How many calls to fib (including the first) does fib(4) make?
Show answer & explanation
Answer: C
C(n) = C(n−1) + C(n−2) + 1 with C(0)=C(1)=1: C(2)=3, C(3)=5, C(4)=9.
int a = 0, b = 5; if (a && b++) { } printf("%d", b); prints:
Show answer & explanation
Answer: B
a is 0, so && short-circuits and b++ is never evaluated; b remains 5.
int x = 2, s = 0; switch (x) { case 1: s += 1; case 2: s += 2; case 3: s += 3; break; default: s += 10; } What is s?
Show answer & explanation
Answer: C
Control enters at case 2: s = 2, falls through to case 3: s = 5, then break exits.
int i; for (i = 0; i < 5; i++); printf("%d", i); prints:
Show answer & explanation
Answer: B
The semicolon makes the loop body empty; the loop ends when i becomes 5 and then printf prints 5.
unsigned char c = 255; c++; printf("%d", c); prints:
Show answer & explanation
Answer: B
c + 1 = 256 is converted back to unsigned char modulo 256, giving 0.
int g(int n) { if (n <= 0) return 0; return 1 + g(n - 1); } For g(5), what is the maximum number of simultaneously active frames of g?
Show answer & explanation
Answer: B
Frames exist for n = 5, 4, 3, 2, 1, 0, i.e., n + 1 = 6 frames at the deepest point.
Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.
printf("%d", 5 > 3 > 1); prints:
Show answer & explanation
Answer: B) 0
Left to right: (5 > 3) = 1, then 1 > 1 = 0.
printf("%d", 10 % 3 * 2); prints:
Show answer & explanation
Answer: A) 2
% and * have equal precedence and associate left to right: (10 % 3) * 2 = 1 * 2 = 2.
int i = 0; while (i++ < 3); printf("%d", i); prints:
Show answer & explanation
Answer: B) 4
Tests: 0<3 (i→1), 1<3 (i→2), 2<3 (i→3), 3<3 false but i→4. Prints 4.
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } What is gcd(48, 18)?
Show answer & explanation
Answer: B) 6
gcd(48,18) → gcd(18,12) → gcd(12,6) → gcd(6,0) = 6.
int x = 1; void f() { x = x + 1; } main calls f() twice and then prints x. Output:
Show answer & explanation
Answer: C) 3
x is a global modified by each call: 1 → 2 → 3.
int m = (4 > 2) ? (1 > 2 ? 10 : 20) : 30; What is m?
Show answer & explanation
Answer: B) 20
4 > 2 is true so the first branch is taken; inside it 1 > 2 is false so the value is 20.
int f(int n) { return n == 0 ? 0 : n + f(n - 1); } What is f(4)?
Show answer & explanation
Answer: B) 10
f(4) = 4 + 3 + 2 + 1 + 0 = 10.
void p(int n) { if (n > 0) { printf("%d", n); p(n - 1); printf("%d", n); } } What does p(2) print?
Show answer & explanation
Answer: A) 2112
Prints 2, recurses: prints 1, recurses (n = 0 does nothing), prints 1 on return, then prints 2: 2 1 1 2.
char c = 'A'; c = c + 2; printf("%c", c); prints:
Show answer & explanation
Answer: C) C
ASCII 'A' is 65; adding 2 gives 67, which is the character 'C'.
How many times does the body of for (i = 10; i > 0; i /= 2) execute?
Show answer & explanation
Answer: B) 4
i takes the values 10, 5, 2, 1 (1/2 = 0 stops the loop): 4 iterations.
Topic FAQs
Is C really call-by-reference when I pass a pointer?
No. C always passes by value; passing a pointer copies the address, and dereferencing it lets the callee modify the caller data, which simulates call-by-reference.
What is the value of an uninitialised local variable?
It is indeterminate (garbage). Only globals and static variables are guaranteed to start at 0.
Why does a switch print several lines when I forget break?
Control falls through into the following case labels until a break or the end of the switch is reached.
How much stack does a recursive function use?
One activation record per active call, so O(depth) space; infinite or too-deep recursion overflows the stack.
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.