chapter
    C Programming, Control Flow and Array Algorithms PYQs for GATE CS

    Solve 13+ C Programming, Control Flow and Array Algorithms previous year questions for GATE CS with answers and detailed solutions. Free sample questions belo

    Try a question

    Answer it here to see how it works. Nothing is recorded until you sign in.

    Question 1
    2026 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider the following three ANSI-C programs, P1, P2, and P3.

    P1P2P3
    #include <stdio.h>
    int a=5;
    int main(){
      int a=7;
      return(0);
    }
    #include <stdio.h>
    int main(){
      int a=5;
      int a=7;
      return(0);
    }
    #include <stdio.h>
    int main(){
      int a=5;
      float a=7;
      return(0);
    }


    Which one of the following statements is true?
    Question 2
    2026 Slot Set1 PYQ
    Level 3: Exam Standard
    Consider the following program in C:

    #include <stdio.h>

    void func(int i, int j) {
      if(i < j) {
        int i = 0;
        while (i < 10) {
          j += 2;
          i++;
        }
      }
      printf("%d", i);
    }

    int main() {
      int i = 9, j = 10;
      func(i, j);
      return 0;
    }

    The output of the program is _________. (answer in integer)

    Note: Assume that the program compiles and runs successfully.
    Question 3
    2025 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider the following C program:

    #include <stdio.h>
    
    int g(int n) {
        return (n+10);
    }
    
    int f(int n) {
        return g(n*2);
    }
    
    int main() {
        int sum, n;
        sum=0;
        for (n=1; n<3; n++)
            sum += g(f(n));
        printf ("%d", sum);
        return 0;
    
    }

    The output of the given C program is ________. (Answer in integer)
    Question 4
    2025 Slot Set2 PYQ
    Level 3: Exam Standard
    int x=126,y=105;
    do {
        if(x>y) x=x-y;
        else y=y-x;
    } while(x!=y);
    
    printf("%d",x);

    The output of the given C code segment is ________. (Answer in integer)
    Question 5
    2025 Slot Set1 PYQ
    Level 3: Exam Standard
    Consider the following C program:

    #include <stdio.h>
    int gate (int n) {
        int d, t, newnum, turn;
        newnum = turn = 0; t=1;
        while (n>=t) t *= 10;
        t /=10;
        while (t>0) {
            d = n/t;
            n = n%t;
            t /= 10;
            if (turn) newnum = 10*newnum + d;
            turn = (turn + 1) % 2;
        }
        return newnum;
    }
    int main () {
        printf ("%d", gate(14362));
        return 0;

    }

    The value printed by the given C program is ______ . (Answer in integer)
    Question 6
    2024 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider the following C program. Assume parameters to a function are evaluated from right to left.

    #include <stdio.h>

    int g(int p) { printf("%d", p); return p; }
    int h(int q) { printf("%d", q); return q; }
    void f(int x, int y) {
    g(x);
    h(y);
    }
    int main() {
     f(g(10),h(20));
    }

    Which one of the following options is the CORRECT output of the above C program?
    Question 7
    2024 Slot Set2 PYQ
    Level 3: Exam Standard
    Consider an array X that contains n positive integers. A subarray of X is defined to be a sequence of array locations with consecutive indices.

    The C code snippet given below has been written to compute the length of the longest subarray of X that contains at most two distinct integers. The code has two missing expressions labelled and .

    int first=0, second=0, len1=0, len2=0, maxlen=0;
    for (int i=0; i < n; i++) {
      if (X[i] == first) {
        len2++; len1++;
      } else if (X[i] == second) {
        len2++;
        len1 = ;
        second = first;
      } else {
        len2 = ;
        len1 = 1; second = first;
      }
      if (len2 > maxlen) {
        maxlen = len2;
      }
      first = X[i];
    }

    Which one of the following options gives the CORRECT missing expressions?

    (Hint: At the end of the i-th iteration, the value of len1 is the length of the longest subarray ending with X[i] that contains all equal values, and len2 is the length of the longest subarray ending with X[i] that contains at most two distinct values.)
    Question 8
    2024 Slot Set1 PYQ
    Level 3: Exam Standard
    Consider the following C program:

    #include <stdio.h>
    int main(){
      int a = 6;
      int b = 0;
      while(a < 10) {
        a = a / 12 + 1;
        a += b;}
      printf("%d", a);
      return 0;}

    Which one of the following statements is CORRECT?
    Question 9
    2024 Slot Set1 PYQ
    Level 3: Exam Standard
    Consider the following C function definition.

    int f(int x, int y) {
      for (int i=0; i<y; i++) {
        x=x+x+y;
      }
      return x;
    }

    Which of the following statements is/are TRUE about the above function?
    Question 10
    2023 PYQ
    Level 3: Exam Standard
    The integer value printed by the ANSI-C program given below is __________.

    #include<stdio.h>

    int funcp(){
        static int x = 1;
        x++;
        return x;
    }

    int main(){
        int x,y;
        x = funcp();
        y = funcp()+x;
        printf("%d\n", (x+y));
        return 0;
    }
    Free preview ends here

    Login to view the complete previous-year questions and solutions

    Creating an account is free. You get the rest of this chapter, step-by-step solutions, and a study plan built around the topics you are actually weak at.

    Why MastersUp

    Personalised first. High quality throughout.

    Most platforms hand everyone the same content. Here the content moves with your performance, topic by topic.

    Built around you, not around a syllabus PDF

    Every answer you give moves your topic-level intelligence rate. The next question, the next revision card and tomorrow's plan all change with it.

    Revision that hits your weak spots

    We only revise topics you have actually attempted and are still below the safe bar on — never the same chapter on repeat.

    Questions calibrated to the real exam

    Each question carries a measured toughness. You are served a rung above your current level, so practice keeps stretching you.

    Notes written for recall, not for volume

    Full lesson cards for first study, curated short-note cards for the last mile — with derivations, traps and exam patterns marked.

    One place for everything

    Notes, chapter practice, previous-year questions, test series and full-length papers — all feeding one picture of your preparation.

    Honest progress

    No vanity streaks. Progress here means chapters mastered and accuracy that held up on harder questions.

    Unlock the whole course

    Full notes and short notes, the complete question bank with worked solutions, mock tests, full-length papers, and an adaptive plan that rebuilds itself as you improve.

    C Programming, Control Flow and Array Algorithms PYQs for GATE CS

    Solve 13+ C Programming, Control Flow and Array Algorithms previous year questions for GATE CS with answers and detailed solutions. Free sample questions below.

    Chapter Roadmap: C Programming, Control Flow and Array Algorithms

    Chapter Journey

    A vertical path through the five topics of this chapter, in the order you will master them.

    1. Loop Tracing and Iterative Computation

    Highest weightage in this chapter. The foundation. You will learn to trace any loop by hand.

    2. Function Calls, Evaluation Order and Static State

    What happens across function boundaries. Static variables and argument evaluation order.

    3. Bitwise and Character Expressions

    Small topic. Tricky on the day of the exam. Shifts, masks, and ASCII arithmetic.

    4. Array Processing and Iterative Algorithms

    Loops meet arrays. Polynomial evaluation, subarrays. The bridge to Data Structures.

    5. Variable Scope, Shadowing and Compilation

    Which variable wins when names collide. Block scope, file scope, shadowing rules.

    What you will be able to do by the end: read any C snippet the exam throws at you, trace it in your head, and write the exact output in under two minutes.

    What Loop Tracing Actually Is

    The Core Idea

    A loop is just a repeated action. Tracing it is just being a careful accountant.

    • You have a small set of variables.
    • The loop changes them, one iteration at a time.
    • Your job: write down every variable, at every step.
    • At the end, read off the answer.

    There is no trick. The only way students lose marks here is by trying to do it in their head and skipping a step. Do not skip a step.

    First principle: a C program is a deterministic state machine. If you know the state before an instruction, you know the state after. Tracing is just applying this, one line at a time.

    C Programming, Control Flow and Array Algorithms: Solved Questions with Step-by-Step Explanations (10 Problems)

    Question 1 · Programming and Data Structures · 2026_Set2 MCQ
    Consider the following three ANSI-C programs, P1, P2, and P3.

    P1P2P3
    #include <stdio.h>
    int a=5;
    int main(){
      int a=7;
      return(0);
    }
    #include <stdio.h>
    int main(){
      int a=5;
      int a=7;
      return(0);
    }
    #include <stdio.h>
    int main(){
      int a=5;
      float a=7;
      return(0);
    }


    Which one of the following statements is true?
    1. A.

      Only P1 will compile without any error

    2. B.

      Only P2 will compile without any error

    3. C.

      Only P3 will compile without any error

    4. D.

      All three programs P1, P2, and P3 will compile without any error

    Correct Answer:

    A

    Step-by-Step Solution

    Insight: C allows variable shadowing across different scopes but forbids redeclaration within the same scope, regardless of type.

    Exam route: Check the scope of each variable declaration. Global vs local is shadowing. Two locals in the same block is redeclaration.

    Learning route:

    1. P1: int a=5; is at file scope. int a=7; is inside main (block scope). The local a shadows the global a. This is perfectly valid C and compiles without error.
    2. P2: int a=5; and int a=7; are both declared inside the exact same block scope (main). This is a redeclaration error. The compiler will reject it.
    3. P3: int a=5; and float a=7; are both in the same block scope. Even though the types differ, C does not allow overloading or redeclaration with different types in the same scope. This is a compilation error.
    4. Therefore, only P1 compiles successfully.

    Trap: Believing that shadowing causes a compilation error or that different types in the same scope are allowed. Shadowing is strictly cross-scope; redeclaration is strictly intra-scope.

    Verification: Compile P1 mentally: global a exists, local a hides it. No conflict. P2: compiler sees two as in main's symbol table -> error. P3: same symbol table, conflicting types -> error.

    Question 2 · Programming and Data Structures · 2026_Set1 NAT
    Consider the following program in C:

    #include <stdio.h>

    void func(int i, int j) {
      if(i < j) {
        int i = 0;
        while (i < 10) {
          j += 2;
          i++;
        }
      }
      printf("%d", i);
    }

    int main() {
      int i = 9, j = 10;
      func(i, j);
      return 0;
    }

    The output of the program is _________. (answer in integer)

    Note: Assume that the program compiles and runs successfully.
    Correct Answer:

    9.00

    Step-by-Step Solution

    Insight: Block scope shadowing hides the outer variable, but the outer variable is untouched and reappears when the block ends.

    Exam route: Parameter i is 9. Inner i is 0, loops to 10. Block ends. printf uses parameter i (9).

    Learning route:

    1. main calls func(9, 10). Inside func, parameter i = 9 and j = 10.
    2. The condition i < j () is true, so the if block is entered.
    3. Inside the if block, int i = 0; is declared. This creates a new local variable i that <b>shadows</b> the parameter i. The parameter i is hidden but still exists with the value 9.
    4. The while loop runs 10 times. The inner i increments from 0 to 10. j increases by 20 (becoming 30).
    5. The if block ends. The inner i goes out of scope and is destroyed.
    6. The printf("%d", i); statement executes. Since the inner i is gone, this refers to the parameter i, which was never modified and remains 9.

    Trap: Assuming the while loop modifies the parameter i (which would output 10), or assuming that redeclaring i inside the block causes a compilation error.

    Verification: Shadowing is strictly scoped. Once the closing brace } of the if block is passed, the shadow is lifted, revealing the original untouched parameter.

    Question 3 · Programming and Data Structures · 2025_Set2 NAT
    Consider the following C program:

    #include <stdio.h>
    
    int g(int n) {
        return (n+10);
    }
    
    int f(int n) {
        return g(n*2);
    }
    
    int main() {
        int sum, n;
        sum=0;
        for (n=1; n<3; n++)
            sum += g(f(n));
        printf ("%d", sum);
        return 0;
    
    }

    The output of the given C program is ________. (Answer in integer)
    Correct Answer:

    46.00

    Step-by-Step Solution

    Insight: Nested function calls require resolving the innermost call first and passing its return value outward.

    Exam route: Trace the loop for n=1 and n=2. For each, compute f(n), then pass the result to g(), and accumulate in sum.

    Learning route:

    1. The loop runs for n=1 and n=2 (since n<3).
    2. Iteration 1 (n=1):
    • Evaluate inner call f(1): calls g(1*2) g(2) returns .
    • Evaluate outer call g(f(1)) g(12) returns .
    • sum becomes .
    1. Iteration 2 (n=2):
    • Evaluate inner call f(2): calls g(2*2) g(4) returns .
    • Evaluate outer call g(f(2)) g(14) returns .
    • sum becomes .
    1. Loop terminates. printf outputs 46.

    Trap: Students sometimes evaluate the outer function first or confuse the argument passed to the outer function. Always resolve from the inside out.

    Verification: . . Total sum = 46.

    Question 4 · Programming and Data Structures · 2025_Set2 NAT
    int x=126,y=105;
    do {
        if(x>y) x=x-y;
        else y=y-x;
    } while(x!=y);
    
    printf("%d",x);

    The output of the given C code segment is ________. (Answer in integer)
    Correct Answer:

    21.00

    Step-by-Step Solution

    Insight: This is the subtraction-based Euclidean algorithm for computing GCD. The loop repeatedly subtracts the smaller value from the larger until both are equal, at which point that common value is the GCD.

    Exam route: Recognize the algorithm immediately, then compute GCD(126, 105) using prime factorization or the modulo-based Euclidean algorithm as a shortcut.

    Learning route:

    1. Initial: x = 126, y = 105.
    2. The do-while loop guarantees at least one iteration.
    3. Iteration 1: x > y (126 > 105), so x = 126 - 105 = 21. State: x=21, y=105.
    4. Iteration 2: x > y is false (21 < 105), so y = 105 - 21 = 84. State: x=21, y=84.
    5. Iteration 3: y = 84 - 21 = 63. State: x=21, y=63.
    6. Iteration 4: y = 63 - 21 = 42. State: x=21, y=42.
    7. Iteration 5: y = 42 - 21 = 21. State: x=21, y=21.
    8. Condition x != y is now false (21 == 21). Loop terminates.
    9. printf("%d", x) prints 21.

    Shortcut verification using prime factorization:

    • Common factors:
    • GCD(126, 105) = 21. Confirmed.

    Alternative verification using modulo-based Euclidean algorithm:

    • GCD = 21. Confirmed.

    Wrong path: A student who makes an arithmetic error in the subtraction chain (e.g., computing instead of 84) would get a wrong final answer. Another error is assuming the loop terminates after the first subtraction and prints 21 immediately without checking the while condition properly, though in this case the answer happens to be correct regardless.

    Generalization: The subtraction-based GCD loop if(x>y) x-=y; else y-=x; while(x!=y) always terminates with both variables equal to GCD(x_initial, y_initial). For large numbers, use the modulo shortcut to verify quickly.

    Question 5 · Programming and Data Structures · 2025_Set1 NAT
    Consider the following C program:

    #include <stdio.h>
    int gate (int n) {
        int d, t, newnum, turn;
        newnum = turn = 0; t=1;
        while (n>=t) t *= 10;
        t /=10;
        while (t>0) {
            d = n/t;
            n = n%t;
            t /= 10;
            if (turn) newnum = 10*newnum + d;
            turn = (turn + 1) % 2;
        }
        return newnum;
    }
    int main () {
        printf ("%d", gate(14362));
        return 0;

    }

    The value printed by the given C program is ______ . (Answer in integer)
    Correct Answer:

    46.00

    Step-by-Step Solution

    Insight: The function extracts digits of n from left to right (most significant to least significant) and selectively builds a new number using alternating digits.

    Exam route: Trace the digit extraction loop. The first while finds the highest power of 10. The second while extracts digits one by one. turn toggles between 0 and 1, acting as a filter.

    Learning route:

    1. n = 14362. First loop sets t = 10000.
    2. Second loop begins. turn = 0, newnum = 0.
    3. Iteration 1: d = 14362 / 10000 = 1. n becomes 4362. t becomes 1000. turn is 0, so if(turn) is false. turn becomes 1.
    4. Iteration 2: d = 4362 / 1000 = 4. n becomes 362. t becomes 100. turn is 1, so newnum = 10*0 + 4 = 4. turn becomes 0.
    5. Iteration 3: d = 362 / 100 = 3. n becomes 62. t becomes 10. turn is 0, skip. turn becomes 1.
    6. Iteration 4: d = 62 / 10 = 6. n becomes 2. t becomes 1. turn is 1, newnum = 10*4 + 6 = 46. turn becomes 0.
    7. Iteration 5: d = 2 / 1 = 2. n becomes 0. t becomes 0. turn is 0, skip. Loop ends.
    8. Returns 46.

    Trap: Misunderstanding the order of extraction. The code extracts from most significant to least significant (left to right). If it extracted right to left, the alternating digits would be different. Also, forgetting that turn starts at 0, meaning the 1st, 3rd, and 5th digits are skipped.

    Verification: The digits of 14362 are 1, 4, 3, 6, 2. The kept digits are at indices 1 and 3 (0-indexed), which are 4 and 6. Concatenating them gives 46.

    Question 6 · Programming and Data Structures · 2024_Set2 MCQ
    Consider the following C program. Assume parameters to a function are evaluated from right to left.

    #include <stdio.h>

    int g(int p) { printf("%d", p); return p; }
    int h(int q) { printf("%d", q); return q; }
    void f(int x, int y) {
    g(x);
    h(y);
    }
    int main() {
     f(g(10),h(20));
    }

    Which one of the following options is the CORRECT output of the above C program?
    1. A.

      20101020

    2. B.

      10202010

    3. C.

      20102010

    4. D.

      10201020

    Correct Answer:

    A

    Step-by-Step Solution

    Insight: Right-to-left evaluation means the rightmost argument is fully evaluated (including side effects like prints) before the left argument.

    Exam route: Evaluate h(20) first (prints 20), then g(10) (prints 10). Then execute f(10, 20), which prints 10 then 20. Total output: 20101020.

    Learning route:

    1. The call is f(g(10), h(20)). The problem explicitly states parameters are evaluated right-to-left.
    2. Rightmost argument: h(20) is evaluated first. It prints 20 and returns 20.
    3. Leftmost argument: g(10) is evaluated next. It prints 10 and returns 10.
    4. Now the function f is called with the evaluated arguments: f(10, 20).
    5. Inside f(int x, int y):
    • g(x) is called g(10). It prints 10.
    • h(y) is called h(20). It prints 20.
    1. Concatenating the prints in order: 20 (from arg eval), 10 (from arg eval), 10 (from f body), 20 (from f body).
    2. Final output string: 20101020.

    Trap: Assuming left-to-right evaluation (which yields 10201020) or assuming the function body executes before arguments are evaluated.

    Verification: Right-to-left argument evaluation is a standard GCC behavior and explicitly mandated by the problem statement.

    Question 7 · Programming and Data Structures · 2024_Set2 MCQ
    Consider an array X that contains n positive integers. A subarray of X is defined to be a sequence of array locations with consecutive indices.

    The C code snippet given below has been written to compute the length of the longest subarray of X that contains at most two distinct integers. The code has two missing expressions labelled and .

    int first=0, second=0, len1=0, len2=0, maxlen=0;
    for (int i=0; i < n; i++) {
      if (X[i] == first) {
        len2++; len1++;
      } else if (X[i] == second) {
        len2++;
        len1 = ;
        second = first;
      } else {
        len2 = ;
        len1 = 1; second = first;
      }
      if (len2 > maxlen) {
        maxlen = len2;
      }
      first = X[i];
    }

    Which one of the following options gives the CORRECT missing expressions?

    (Hint: At the end of the i-th iteration, the value of len1 is the length of the longest subarray ending with X[i] that contains all equal values, and len2 is the length of the longest subarray ending with X[i] that contains at most two distinct values.)
    1. A.

      len1+1 len2+1

    2. B.

      1 len1+1

    3. C.

      1 len2+1

    4. D.

      len2+1 len1+1

    Correct Answer:

    B

    Step-by-Step Solution

    Insight: This is a sliding window algorithm tracking the longest subarray with at most two distinct elements using space. len1 tracks the suffix of identical elements, and len2 tracks the valid two-element window.

    Exam route: Analyze the state transitions when a new element matches the older distinct value (second) versus when it is a completely new third value.

    Learning route:

    1. len1 maintains the length of the contiguous trailing sequence of identical elements ending at X[i-1].
    2. len2 maintains the longest valid subarray ending at X[i-1] with at most two distinct values.
    3. When X[i] == first: The element extends the current identical suffix. Both len1 and len2 increment.
    4. When X[i] == second: The element matches the older distinct value in our window. The window extends (len2++), but the trailing identical suffix is broken and restarts at length 1. Thus, (P) must be 1. The roles of first and second swap.
    5. When X[i] is a third distinct value: The window must shrink to keep only the previous identical suffix plus this new element. The new window length is exactly the old len1 plus 1. Thus, (Q) must be len1 + 1. len1 resets to 1.

    Trap: Confusing len1 and len2 updates. If you set (Q) to len2 + 1, you incorrectly include elements from before the trailing identical suffix, violating the "at most two distinct" rule when a third value appears.

    Verification: Trace array [2, 2, 3, 2].

    • i=0 (2): len1=1, len2=1.
    • i=1 (2): len1=2, len2=2.
    • i=2 (3): 3rd value? No, first=2, second=0. It goes to else, len2 = len1+1 = 3. len1=1. second=2, first=3.
    • i=3 (2): Matches second (2). len2++ (4). len1 = 1. first=2, second=3. Window [2,2,3,2] is valid, length 4. Correct.
    Question 8 · Programming and Data Structures · 2024_Set1 MCQ
    Consider the following C program:

    #include <stdio.h>
    int main(){
      int a = 6;
      int b = 0;
      while(a < 10) {
        a = a / 12 + 1;
        a += b;}
      printf("%d", a);
      return 0;}

    Which one of the following statements is CORRECT?
    1. A.

      The program prints 9 as output

    2. B.

      The program prints 10 as output

    3. C.

      The program gets stuck in an infinite loop

    4. D.

      The program prints 6 as output

    Correct Answer:

    C

    Step-by-Step Solution

    Insight: Integer division truncates toward zero, creating a fixed point that prevents the loop variable from ever reaching the termination condition.

    Exam route: Evaluate just two iterations. Observe that a maps to 1 and then stays at 1 forever. The loop never terminates.

    Learning route:

    1. Initial state: a = 6, b = 0. Check condition: 6 < 10 is true, enter loop.
    2. Iteration 1:
    • a = a / 12 + 1. In C integer arithmetic, 6 / 12 = 0 (truncation toward zero).
    • So a = 0 + 1 = 1.
    • a += b gives a = 1 + 0 = 1.
    1. Check condition: 1 < 10 is true, continue.
    2. Iteration 2:
    • a = 1 / 12 + 1. Integer division: 1 / 12 = 0.
    • So a = 0 + 1 = 1.
    • a += 0 gives a = 1.
    1. The value of a is now pinned at 1. Every subsequent iteration produces the same result. The condition a < 10 remains true forever.
    2. The program enters an infinite loop and never reaches printf.

    Wrong path producing "prints 10": A student who mentally evaluates 6/12 as 0.5 and rounds up would get a = 0.5 + 1 = 1.5, then perhaps a = 2 on the next step, and eventually reach 10. But C integer division strictly truncates, never rounds.

    Wrong path producing "prints 6": A student who assumes the loop body never executes (perhaps misreading the condition as a > 10) would select this. But 6 < 10 is clearly true.

    Verification: The function has a fixed point at since . Since the loop condition is satisfied at this fixed point, the loop cannot terminate.

    Generalization: Whenever a while-loop updates its control variable using integer division by a larger number, check whether the variable reaches a fixed point below the termination threshold. If so, the loop is infinite.

    Question 9 · Programming and Data Structures · 2024_Set1 MSQ
    Consider the following C function definition.

    int f(int x, int y) {
      for (int i=0; i<y; i++) {
        x=x+x+y;
      }
      return x;
    }

    Which of the following statements is/are TRUE about the above function?
    1. A.

      If the inputs are , then the return value is greater than

    2. B.

      If the inputs are , then the return value is greater than

    3. C.

      If the inputs are , then the return value is less than

    4. D.

      If the inputs are , then the return value is greater than

    Correct Answer:

    ["B","D"]

    Step-by-Step Solution

    Insight: The loop computes the linear recurrence exactly times, yielding a closed-form involving powers of 2.

    Exam route: Derive the closed form , then compare each option's result against the stated power-of-2 bound.

    Learning route:

    1. The loop runs from i=0 to i=y-1, so exactly iterations.
    2. Each iteration applies .
    3. Unrolling:
    • After 1 step:
    • After 2 steps:
    • After 3 steps:
    1. General form after steps: .
    2. After steps (the loop bound): .

    Now test each option:

    Option A (): . Compare with . Since , the statement "greater than " is FALSE.

    Option B (): . This is clearly . TRUE.

    Option C (): Result is 30710. Compare with . Since , the statement "less than " is FALSE.

    Option D (): . This is . TRUE.

    Verification by back-substitution: For Option B, , which is indeed . Confirmed.

    Generalization: Any loop of the form x = a*x + b repeated times yields . Recognize this pattern to avoid tedious manual tracing.

    Question 10 · Programming and Data Structures · 2023 NAT
    The integer value printed by the ANSI-C program given below is __________.

    #include<stdio.h>

    int funcp(){
        static int x = 1;
        x++;
        return x;
    }

    int main(){
        int x,y;
        x = funcp();
        y = funcp()+x;
        printf("%d\n", (x+y));
        return 0;
    }
    Correct Answer:

    7.00

    Step-by-Step Solution

    Insight: A static local variable retains its value across function calls, while local variables in main are independent. The question tests whether you can track two distinct variables named x in different scopes.

    Exam route: Trace the static x inside funcp across two calls, then combine with the local x and y in main.

    Learning route:

    1. First call x = funcp();:
    • Inside funcp: static x is initialized to 1 (this happens only once, ever).
    • x++ increments static x to 2.
    • Returns 2.
    • In main: local variable x is assigned 2.
    1. Second call y = funcp() + x;:
    • Inside funcp: static x retains its value of 2 from the previous call.
    • x++ increments static x to 3.
    • Returns 3.
    • In main: the expression evaluates to 3 + 2 (the local x in main is still 2).
    • Local y is assigned 5.
    1. Print: printf("%d\n", (x+y)) prints 2 + 5 = 7.

    Wrong path producing 5: A student who assumes static x resets to 1 on every call would get: first call returns 2, second call also returns 2, so y = 2 + 2 = 4, and x + y = 2 + 4 = 6. Or they might confuse the two x variables entirely.

    Wrong path producing 9: A student who thinks the local x in main is the same variable as the static x in funcp might set x = 3 after the second call, then compute y = 3 + 3 = 6 and print 3 + 6 = 9.

    Verification: Static x inside funcp: 1 2 3 (across two calls). Local x in main: 2 (set once, never modified again). Local y: 5. Sum: 7. Confirmed.

    Generalization: Variables with the same name in different scopes are completely independent. Static variables persist across calls; automatic variables do not. Always maintain separate columns for each scope in your trace.

    More previous year questions (pyqs) in this unit