Skip to main content

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.

~4 hrs ~1.5–2 marks · High 10 samples · 10 practice · 10 cards

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)OperatorsAssociativity
1() [] -> . postfix ++ --Left to right
2unary + - ! ~ * & 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.

Short-circuit evaluation: a equals 0 makes && skip b++ so b stays 5, versus a equals 1 where b++ runs
Left operand 0 in && means the right side never runs — the side effect (b++) is lost.

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.
nfib calls C(n)Max depth of stack (frames)
011
111
232
353
494

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).

Runtime stack showing frames for main, g(3), g(2) and g(1) with parameter n and return address
Each call pushes a frame (n + return address); depth = frames alive at once.

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.

Two versions of f(3): print before the recursive call outputs 3 2 1, print after outputs 1 2 3
Where printf sits relative to the recursive call decides the output order.

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.
Exam pattern · 10 questions

GATE sample questions & answers

10 GATE-style MCQs for C Programming with full explanations. Attempt each question before revealing the answer.

Q1 Integer division and remainder

What is the output of printf("%d", 7/2 + 7%2 + -7/2); in C99 with 32-bit int?

  • A) 0
  • B) 1
  • C) 2
  • D) 7
Show answer & explanation

Answer: B

7/2 = 3, 7%2 = 1, (-7)/2 = -3 (truncation toward zero). 3 + 1 + (−3) = 1.

Q2 Static storage

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?

  • A) 3
  • B) 6
  • C) 9
  • D) 0
Show answer & explanation

Answer: B

The static variable persists: the calls return 1, 2, 3, so the sum is 6.

Q3 Call by value

void inc(int x) { x = x + 1; } int main() { int a = 5; inc(a); printf("%d", a); } prints:

  • A) 6
  • B) 5
  • C) 0
  • D) Garbage
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.

Q4 Recursion order

void f(int n) { if (n == 0) return; f(n - 1); printf("%d ", n); } What does f(3) print?

  • A) 3 2 1
  • B) 1 2 3
  • C) 0 1 2 3
  • D) 3
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.

Q5 Recursion tree

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?

  • A) 5
  • B) 8
  • C) 9
  • D) 15
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.

Q6 Short-circuit evaluation

int a = 0, b = 5; if (a && b++) { } printf("%d", b); prints:

  • A) 4
  • B) 5
  • C) 6
  • D) 0
Show answer & explanation

Answer: B

a is 0, so && short-circuits and b++ is never evaluated; b remains 5.

Q7 Switch fall-through

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?

  • A) 2
  • B) 3
  • C) 5
  • D) 15
Show answer & explanation

Answer: C

Control enters at case 2: s = 2, falls through to case 3: s = 5, then break exits.

Q8 Empty loop body

int i; for (i = 0; i < 5; i++); printf("%d", i); prints:

  • A) 4
  • B) 5
  • C) 0
  • D) Nothing; compile error
Show answer & explanation

Answer: B

The semicolon makes the loop body empty; the loop ends when i becomes 5 and then printf prints 5.

Q9 Unsigned wrap-around

unsigned char c = 255; c++; printf("%d", c); prints:

  • A) 256
  • B) 0
  • C) -1
  • D) 255
Show answer & explanation

Answer: B

c + 1 = 256 is converted back to unsigned char modulo 256, giving 0.

Q10 Runtime stack depth

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?

  • A) 5
  • B) 6
  • C) 4
  • D) 1
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.

Topic drill · 10 questions

10 practice questions — C Programming

Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.

P1

printf("%d", 5 > 3 > 1); prints:

  • A) 1
  • B) 0
  • C) 3
  • D) Compile error
Show answer & explanation

Answer: B) 0

Left to right: (5 > 3) = 1, then 1 > 1 = 0.

P2

printf("%d", 10 % 3 * 2); prints:

  • A) 2
  • B) 1
  • C) 6
  • D) 20
Show answer & explanation

Answer: A) 2

% and * have equal precedence and associate left to right: (10 % 3) * 2 = 1 * 2 = 2.

P3

int i = 0; while (i++ < 3); printf("%d", i); prints:

  • A) 3
  • B) 4
  • C) 2
  • D) 0
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.

P4

int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } What is gcd(48, 18)?

  • A) 3
  • B) 6
  • C) 12
  • D) 18
Show answer & explanation

Answer: B) 6

gcd(48,18) → gcd(18,12) → gcd(12,6) → gcd(6,0) = 6.

P5

int x = 1; void f() { x = x + 1; } main calls f() twice and then prints x. Output:

  • A) 1
  • B) 2
  • C) 3
  • D) 0
Show answer & explanation

Answer: C) 3

x is a global modified by each call: 1 → 2 → 3.

P6

int m = (4 > 2) ? (1 > 2 ? 10 : 20) : 30; What is m?

  • A) 10
  • B) 20
  • C) 30
  • D) 1
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.

P7

int f(int n) { return n == 0 ? 0 : n + f(n - 1); } What is f(4)?

  • A) 4
  • B) 10
  • C) 24
  • D) 6
Show answer & explanation

Answer: B) 10

f(4) = 4 + 3 + 2 + 1 + 0 = 10.

P8

void p(int n) { if (n > 0) { printf("%d", n); p(n - 1); printf("%d", n); } } What does p(2) print?

  • A) 2112
  • B) 2121
  • C) 1221
  • D) 2211
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.

P9

char c = 'A'; c = c + 2; printf("%c", c); prints:

  • A) A
  • B) B
  • C) C
  • D) 67
Show answer & explanation

Answer: C) C

ASCII 'A' is 65; adding 2 gives 67, which is the character 'C'.

P10

How many times does the body of for (i = 10; i > 0; i /= 2) execute?

  • A) 3
  • B) 4
  • C) 5
  • D) 10
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.

Quick revision · 10 cards

10 flashcards — C Programming

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 What is the difference between call-by-value and call-by-reference in C?
Q2 What does the static keyword do for a local variable in C?
Q3 What information is stored in a function activation record on the runtime stack?
Q4 How do integer division and the remainder operator behave with negative operands in C99?
Q5 What is short-circuit evaluation of && and || in C?
Q6 What happens in a C switch statement when a case does not end with break?
Q7 What are the default initial values of global variables, static variables, and uninitialised auto locals?
Q8 Why does the naive recursive Fibonacci function take exponential time?
Q9 What is the difference between the = and == operators in C?
Q10 What causes a stack overflow in a recursive C program?