Function func(i,j) is called with i=9,j=10. If i<j, an inner block declares a new int i=0 and loops while that inner i<10, adding 2 to j and incrementing the inner i. After the block, printf("%d",i) executes. Determine the printed integer.
Answer & solution
Official answer: 9
Step through it (42 steps)
Givens and goal
Function func(i,j) is called with i=9,j=10. If i<j, an inner block declares a new int i=0 and loops while that inner i<10, adding 2 to j and incrementing the inner i. After the block, printf("%d",i) executes. Determine the printed integer.
Approach
Track each distinct variable object and which declaration each occurrence of i refers to.
Step-by-step solution
1. The function receives its own parameter i with value 9 and parameter j with value 10. The initial comparison succeeds. 2. Inside the conditional block, a new local i is declared. It shadows the parameter i only within that block. The loop increments this inner variable from 0 to 10; it does not alter the parameter i. 3. The loop also increases the function-local j, which has no effect on the printed expression. When execution leaves the block, the inner i goes out of scope. 4. The print statement is outside the block. Its identifier i therefore refers to the parameter, still equal to 9. The output is 9, with no newline implied by the shown format string.
Common error: Shadowing creates a different object; it is not assignment to the outer object.
Scope trace
Point Parameter i Inner i Parameter j
Function entry 9 absent 10
Inner declaration 9 0 10
After ten loop iterations 9 10 30
At printf 9 absent 30
The table makes clear that reaching inner i=10 does not imply that printf prints 10. The condition uses the parameter before the inner declaration is reached, whereas the loop uses the inner object.
For a nonempty singly linked list, getListSize(head) returns 1 if E1 is true and otherwise returns E2. Choose between base tests head==NULL or head->next==NULL, and recursive expressions 1+getListSize(head) or 1+getListSize(head->next).
Your answer
Answer & solution
Official answer: B
Givens and goal
For a nonempty singly linked list, getListSize(head) returns 1 if E1 is true and otherwise returns E2. Choose between base tests head==NULL or head->next==NULL, and recursive expressions 1+getListSize(head) or 1+getListSize(head->next).
Approach
Match the base return value 1 to a one-node list and ensure recursion moves to a strictly shorter suffix.
Step-by-step solution
1. The input list is nonempty, so the current head points to a node. A one-node list is recognized by a null next pointer, and its length is 1. 2. If a next node exists, the tail beginning there is also nonempty. The total length is one for the current node plus the recursively computed tail length. This supplies the base condition and recursive expression in B. 3. Induction proves correctness: length 1 returns 1; assuming the routine counts a tail of length n−1, the recursive case returns 1+(n−1)=n. 4. Passing the unchanged head recursively never decreases the problem size and does not terminate on longer lists. Using head==NULL as the base test while returning 1 gives an extra count for the empty suffix. These defects eliminate the other choices.
Assumption: As usual for a finite singly linked list, the chain is acyclic. The question's recursion would not terminate on a cyclic structure.
Trace for three nodes A→B→C→NULL: the call at C detects next==NULL and returns 1; the call at B returns 1+1=2; the call at A returns 1+2=3. With a head==NULL base returning 1, even a one-node input would instead return 1+1=2. With an unchanged-head recursive call, any list longer than one node recurses forever rather than reaching the last node.
The recursive functions are bar(1)=0 and bar(n)=1+bar(n/2) otherwise, using C integer division; foo(1)=1 and foo(n)=1+foo(bar(n)) otherwise. Find the smallest positive integer n for which foo(n)=5.
Answer & solution
Official answer: 65536
Step through it (2 calls)
Givens and goal
The recursive functions are bar(1)=0 and bar(n)=1+bar(n/2) otherwise, using C integer division; foo(1)=1 and foo(n)=1+foo(bar(n)) otherwise. Find the smallest positive integer n for which foo(n)=5.
Approach
First identify bar as a floor logarithm, then work backwards through the thresholds for successive foo return values.
Step-by-step solution
1. For positive n, integer division by 2 repeatedly halves n with truncation. If 2^m≤n<2^(m+1), exactly m divisions are needed to reach 1. Hence bar(n)=floor(log₂n). 2. Therefore foo(n)=1+foo(floor(log₂n)) for n>1, with foo(1)=1. A foo call counts one level and continues with its much smaller floor-logarithm argument. 3. Let a_j be the smallest input with return value j. The base is a₁=1. To obtain one extra level, floor(log₂n) must reach at least the smallest input a_j needed for the previous level. The least n with floor(log₂n)=a_j is n=2^(a_j). 4. Thus the successive thresholds are a₁=1, a₂=2, a₃=4, a₄=16, a₅=2^16=65536. Monotonicity of floor(log₂n) and of these level thresholds shows no smaller input can skip ahead to five levels. 5. Verify directly: bar(65536)=16, bar(16)=4, bar(4)=2, bar(2)=1. The foo chain is 65536→16→4→2→1, giving return values 5→4→3→2→1 when read from the outer call inward. 6. The requested integer is 65536. The division is integer division; treating bar as an unrounded real logarithm would not model the code.
In the conventional C runtime model, which object is stored in the heap? A function-local static variable; B ordinary function-local integer array; C integer array allocated by malloc; D function return address.
Your answer
Answer & solution
Official answer: C
Givens and goal
In the conventional C runtime model, which object is stored in the heap? A function-local static variable; B ordinary function-local integer array; C integer array allocated by malloc; D function return address.
Approach
Compare storage duration and allocation mechanism rather than source-code location.
Step-by-step solution
1. malloc requests dynamically allocated storage whose lifetime extends until it is released, typically by free. Conventional runtimes manage this storage in the heap. Thus C is the intended answer. 2. A local static variable exists for the program lifetime and conventionally occupies a static data region, despite its name having block scope. Scope does not determine storage duration. 3. An ordinary non-static local array has automatic storage duration and is conventionally placed in a stack frame. A return address is part of calling state, often on a stack or in an architecture-specific register. 4. A local pointer holding the malloc result can itself be in a stack frame while the array it points to is in the heap. The C standard specifies storage behavior, not physical regions literally named stack and heap; the answer uses the stated runtime convention.
Each program includes stdio.h and has main returning 0. P1: file-scope int a=5; inside main, int a=7;. P2: inside one main block, int a=5; int a=7;. P3: inside one main block, int a=5; float a=7;. Which compiles without a required error? A only P1; B only P2; C only P3; D all.
Your answer
Answer & solution
Official answer: A
Givens and goal
Each program includes stdio.h and has main returning 0. P1: file-scope int a=5; inside main, int a=7;. P2: inside one main block, int a=5; int a=7;. P3: inside one main block, int a=5; float a=7;. Which compiles without a required error? A only P1; B only P2; C only P3; D all.
Approach
Check whether declarations inhabit different scopes or attempt to define the same local identifier twice.
Step-by-step solution
1. P1 has an outer file-scope object and a distinct inner block-scope object. The inner a legally shadows the outer a inside main. The two definitions do not conflict because they are in different scopes. 2. P2 has two initialized definitions of the same ordinary automatic identifier in one block. It is not assignment to an existing object: the repeated type keyword introduces a second declaration/definition, which violates the constraints. 3. P3 also redeclares a in the same block, and additionally changes its type from int to float. This is not legal shadowing, because there is no nested inner block. 4. Only P1 is valid under the intended ANSI-C rules, so A. A compiler may issue a shadowing warning for P1, but an optional warning does not make the program invalid.
Find the printed c for this statement sequence in main: int *ptr,a,b,c; a=5; b=11; c=20; ptr=&a; *ptr=c; ptr=&c; a=*(&b); c=*ptr-a; printf("%d",c);. Assume successful compilation and execution.
Answer & solution
Official answer: 9
Step through it (14 steps)
Givens and goal
Find the printed c for this statement sequence in main: int *ptr,a,b,c; a=5; b=11; c=20; ptr=&a; *ptr=c; ptr=&c; a=*(&b); c=*ptr-a; printf("%d",c);. Assume successful compilation and execution.
Approach
Track both the pointer target and the object values after every assignment.
Step-by-step solution
1. Initially a=5,b=11,c=20. The assignment ptr=&a stores a’s address in ptr; it does not change any integer value. 2. Then *ptr=c writes the current value of c into the object pointed to by ptr, which is a. The state becomes a=20,b=11,c=20, with ptr still pointing to a. 3. Next ptr=&c redirects the pointer to c without copying any old pointed-to value. The expression *(&b) is simply b, so a=*(&b) sets a=11. Now a=11,b=11,c=20 and ptr points to c. 4. In c=*ptr-a, the right-hand side reads the old value c=20 through ptr and subtracts a=11. The assignment therefore stores c=9, and printf prints 9. 5. This assignment is well-defined: the old c is read to calculate its new value. The crucial distinction is between changing ptr itself and assigning through *ptr to the current target.
The function computes length=end+1−start. It returns 0 if length<1 or start<0 or end<0. Otherwise if length%3==0 it returns func(start+1,end); if length%3==1 it returns 1+func(start,end−1); else it returns func(start+2,end). Find the maximum possible returned value for defined, non-overflowing C executions.
Answer & solution
Official answer: 1
Givens and goal
The function computes length=end+1−start. It returns 0 if length<1 or start<0 or end<0. Otherwise if length%3==0 it returns func(start+1,end); if length%3==1 it returns 1+func(start,end−1); else it returns func(start+2,end). Find the maximum possible returned value for defined, non-overflowing C executions.
Approach
Follow how the interval length moves between residue classes modulo three.
Step-by-step solution
1. For valid endpoints let L=end+1−start>0. The first branch changes L to L−1, the second to L−1 while adding 1, and the third to L−2. Every valid recursive step strictly decreases L, so it eventually reaches a base case. 2. If L≡0 mod 3, the next length is L−1≡2. The following step subtracts 2, reaching L−3≡0. This 0→2→0 cycle never enters residue 1 and therefore contributes no increment. 3. If L≡2 mod 3, its first step goes directly to L−2≡0, followed by the same zero-contribution cycle. If L≡1 mod 3, it adds 1 once and moves to L−1≡0, after which no further increments occur. 4. Invalid endpoints return zero immediately. The value 1 is attainable with start=end=0: length=1, so the function returns 1+func(0,−1)=1+0. 5. Therefore the maximum is 1. This analysis assumes representable arithmetic; evaluating end+1 or changing endpoints beyond signed-int limits can cause undefined behavior and is not a valid counterexample returning a larger defined integer.
C function foo(int *p,int x) executes *p=x. In main, a=20,b=25, pointer z is assigned &a, then foo(z,b) is called and a is printed. What integer is printed?
Answer & solution
Official answer: 25
Approach: Distinguish copying an argument from modifying the object that a copied pointer designates. Initially a contains 20 and b contains 25. The assignment z=&a makes z hold the address of a. On calling foo(z,b), the parameter p receives a copy of that same address, while x receives the value 25. Inside foo, the expression *p is the integer object at p’s address, which is main’s a. Therefore *p=x stores 25 into a. Returning from foo discards its local parameter objects but does not undo the write to a. The subsequent printf of a prints 25. C still passes arguments by value: p itself is copied, but the copied address can be dereferenced to change an object owned by the caller. If the function had assigned only p or x, that would be a different operation; the dereferencing assignment is decisive.
In C, foo(S,size) returns 0 for size=0, 1 for size=1, otherwise returns 1+foo(S+1,size−1) if S[0]≠S[1], and foo(S+1,size−1) otherwise. main prints foo(A,9) for A={0,1,2,2,2,0,0,1,1}. What is printed?
Answer & solution
Official answer: 5
Step through it (17 steps)
Approach: Interpret each recursive step as testing one adjacent boundary, with the final single element supplying the first run count. For a nonempty array, every call with size greater than one advances the pointer by one and decreases size by one. It adds 1 exactly when the two currently adjacent values differ. The size-one base case returns 1, so the total is 1 plus the number of adjacent changes. Here the adjacent-change indicators are 1,1,0,0,1,0,1,0 for the pairs (0,1),(1,2),(2,2),(2,2),(2,0),(0,0),(0,1),(1,1). Their sum is 4; adding the base-case 1 yields 5. Equivalently, the maximal equal-value runs are [0], [1], [2,2,2], [0,0], [1,1]. There are five runs, so the program prints 5. It does not count distinct numerical values; although only 0,1,2 occur, repeated values separated into different runs contribute separately.
Function gate(n) initializes newnum=turn=0,t=1; multiplies t by 10 while n≥t, then divides t by 10. While t>0 it sets d=n/t, n=n%t, t=t/10; if turn is 1 it appends d using newnum=10*newnum+d; then sets turn=(turn+1)%2. All divisions are integer divisions. What does gate(14362) print?
Answer & solution
Official answer: 46
Approach: The first loop finds the highest decimal place value. The second consumes digits from left to right and retains alternating positions. For n=14362, t grows through 1,10,100,1000,10000,100000. The condition then fails and t is divided by 10, giving 10000. The digit iterations are: d=1, remainder 4362, turn=0, so skip; d=4, remainder 362, turn=1, so newnum=4; d=3, remainder 62, turn=0, so skip; d=6, remainder 2, turn=1, so newnum=10×4+6=46; d=2, remainder 0, turn=0, so skip. The place value becomes zero and the loop ends. The program therefore prints 46, the digits in positions two and four from the left. The alternating flag is tested before it is toggled, so the first digit is skipped. For this concrete input all arithmetic fits in int; possible overflow for much larger arguments is irrelevant to this execution.
A C program initializes char a[30]="@#Hello World!"; calls stringcopy(a,a+2); and prints a using printf("%s\n",a). The user-defined function is: void stringcopy(char *s,char *t) { while (*t) *s++ = *t++; } What is printed before the newline? Options: A. @#Hello World!; B. Hello World!; C. ello World!; D. Hello World!d!.
Your answer
Answer & solution
Official answer: D
Step through it (34 steps)
The source pointer begins at index 2, the H, and the destination begins at index 0. Initially the string occupies indices 0 through 13 and its null terminator is at index 14. The loop copies the 12 non-null characters “Hello World!” from source indices 2…13 into destination indices 0…11.
After the last exclamation mark is copied, t points at index 14. The condition *t is now zero, so the loop stops before copying that null terminator. Destination indices 12 and 13 were never overwritten and still contain the original d and !. The first terminating null remains at index 14. Thus the complete printed sequence is “Hello World!d!”, followed by the newline: D.
The key mistake in the function is failing to copy or append '\0'. This is an explicit forward-copy loop that reads two positions ahead of its writes, so previously overwritten bytes do not corrupt later reads. It should not be confused with calling the standard strcpy on overlapping arrays, which would have undefined behavior.
Find the integer printed by this C fragment: int x=126,y=105; do { if(x>y) x=x-y; else y=y-x; } while(x!=y); printf("%d",x);
Answer & solution
Official answer: 21
Step through it (21 steps)
Trace the pair (x,y) after each execution of the body: (126,105) → (21,105) → (21,84) → (21,63) → (21,42) → (21,21). At the first step x>y, so only x changes. Thereafter y>x until equality is reached, so y is reduced repeatedly by 21. The loop test sees x==y after the fifth iteration and stops. The printed x is 21.
This is the subtraction version of Euclid's algorithm. Replacing a larger positive integer by its difference with the smaller preserves the set of common divisors, and hence the gcd. At termination the two equal positive values must equal gcd(126,105)=21. Remember that a do-while executes the body before testing its condition; here the initial values differ, so that distinction does not alter the trace. Answer: 21.
Find the integer output of this C fragment: int a; int arr[5]={30,50,10}; int *ptr; ptr=&arr[0]+1; a=*ptr; (*ptr)++; ptr++; printf("%d",a+(*ptr)+arr[1]);
Answer & solution
Official answer: 111
Step through it (12 steps)
Array initialization yields arr=[30,50,10,0,0]; omitted entries are zero-initialized. Pointer arithmetic &arr[0]+1 advances by one int element, so ptr initially points to arr[1], whose value is 50. The assignment a=*ptr copies 50 into a.
The parentheses in (*ptr)++ make the increment apply to the pointed-to value. Hence arr[1] becomes 51 while ptr stays at arr[1]. The copied variable a remains 50. The next statement ptr++ instead increments the pointer itself, moving it to arr[2], whose value is 10.
At the print, the three terms are a=50, *ptr=10, and arr[1]=51. Their sum is 50+10+51=111. The operations occur in separate statements, so their sequencing is unambiguous. Confusing (*ptr)++ with *ptr++ would mix up value mutation and pointer advancement and give the wrong trace. Answer: 111.
A C program defines g(n)=n+10 and f(n)=g(n*2). It initializes sum=0 and executes for(n=1;n<3;n++) sum += g(f(n)); then prints sum. What integer is printed?
Answer & solution
Official answer: 46
Resolve the function composition from the innermost call outward. Since g(t)=t+10, f(n)=g(2n)=2n+10. Applying g again gives g(f(n))=f(n)+10=2n+20. The two additions of 10 arise from two separate g calls; the outer one does not double its input.
The loop condition is n<3, so it runs for n=1 and n=2 only. At n=1, f(1)=12 and g(f(1))=22, taking sum from 0 to 22. At n=2, f(2)=14 and g(f(2))=24, taking sum to 46. After incrementing n to 3 the condition fails, and no n=3 term is added. The printed value is 46.
A C program initializes int a=6, b=0, then executes while(a<10) { a=a/12+1; a+=b; }, followed by printf("%d",a). What happens in the intended execution model? A prints 9; B prints 10; C infinite loop; D prints 6.
Your answer
Answer & solution
Official answer: C
Approach: Trace the first iteration, then determine whether the loop reaches a repeating state. Both operands of a/12 are integers. 1. The initial test 6<10 is true. Integer division gives 6/12=0, so a=a/12+1 sets a to 1. 2. The following a+=b adds zero, because b was initialized to 0 and is never changed. The first iteration ends with a=1, b=0. 3. If an iteration starts with a=1, then 1/12=0, and the same two assignments leave a=1 again. This state is therefore preserved indefinitely. 4. The condition a<10 remains true, so control never reaches the printf after the loop. Answer: C. The expression contains “+1”, but it does not mean a is incremented each time: a is first replaced by the quotient a/12. This is the textbook execution interpretation of the supplied program. The printed program uses typographic double quotation marks. Taken literally these are not valid C delimiters, so the program does not compile as printed. The answer above follows the intended textbook interpretation with ASCII quote delimiters.
main calls fX once. The function has local char a; it reads a=getchar(), recursively calls fX if a is not newline, then prints a with putchar if a is not newline. Input is 1234 followed by newline. A no termination; B termination with no output; C termination with 4321; D termination with 1234.
Your answer
Answer & solution
Official answer: C
Approach: Distinguish the order in which recursive calls read characters from the order in which suspended calls resume printing. 1. The first call stores '1' in its own local a and calls fX again before reaching putchar. The next calls similarly store '2', '3' and '4'. Each call has a separate local variable. 2. A fifth call reads the newline. Both conditions are false, so this call neither recurses nor prints and returns immediately. 3. The suspended call holding '4' now continues at its second condition and prints 4. Returning again prints 3, then 2, then 1. 4. Once the first call returns, main terminates. The newline itself is never printed. Answer: C, output 4321. Printing before the recursive call would preserve input order; printing after it reverses order. The explicitly supplied newline is the stopping condition, so no assumption about reading past end-of-file is needed. The printed program uses typographic single quotation marks. Taken literally these are not valid C delimiters, so the program does not compile as printed. The answer above follows the intended textbook interpretation with ASCII quote delimiters.
Evaluate 3+1+5*2/7+2−4−7−6/2 using these rules: + has highest precedence and associates left; − is next and associates right; * is next and associates right; / is lowest and associates right. All arithmetic is integer arithmetic.
Answer & solution
Official answer: 6
Approach: Build the grouping from the stated table, not from ordinary mathematical or C precedence. Associativity decides grouping only among operators at the same precedence. 1. Highest-precedence additions group (3+1+5)=9 and (7+2)=9. The expression becomes 9*2/9−4−7−6/2. 2. Subtraction has higher precedence than multiplication and division and is right-associative. Its group is 9−(4−(7−6)). Evaluate inward: 7−6=1, 4−1=3, 9−3=6. 3. The expression is now 9*2/6/2. Multiplication is next, giving 18/6/2. 4. Division is right-associative, so this means 18/(6/2), not (18/6)/2. The inner quotient is 3 and the result is 18/3=6. Answer: 6. A fully parenthesized form is ((3+1)+5)*2 / (((7+2)−(4−(7−6)))/2). Both actual divisions are exact, so no integer-rounding issue arises.
The C function f(int x,int y) runs for(int i=0;i<y;i++){x=x+x+y;} and returns x. Which statements hold in the intended integer model? A f(20,10)>2²⁰; B f(20,20)>2²⁰; C f(20,10)<2¹⁰; D f(10,20)>2²⁰. The exponents are 20 and 10, not the decimal numbers 220 and 210.
Select all that apply
Answer & solution
Official answer: B, D
Approach: Derive a closed form for the loop instead of expanding twenty iterations individually. 1. Let x_k be the value after k iterations, with initial value x_0. Since y is unchanged, x_(k+1)=2x_k+y. Adding y gives x_(k+1)+y=2(x_k+y). 2. Therefore x_k+y=2^k(x_0+y), or x_k=2^k(x_0+y)−y. For the positive inputs listed, the loop performs exactly y iterations. 3. f(20,10)=30×2¹⁰−10=30,710. This exceeds 2¹⁰=1,024 but is below 2²⁰=1,048,576, so both A and C are false. 4. f(20,20)=40×2²⁰−20=41,943,020, and f(10,20)=30×2²⁰−20=31,457,260. Both exceed 2²⁰, making B and D true. Answer: B and D. This trace assumes an int wide enough for these values, such as a 32-bit signed int. On a narrow implementation signed overflow would invalidate the mathematical trace; the original does not specify int width.
Trace argument evaluation separately from function execution
Functions & Parameter Passing
Tap to enlarge
Functions g(p) and h(q) each print their integer argument with no separator and return it. Function f(x,y) calls g(x), then h(y). main calls f(g(10),h(20)). Assume argument expressions are evaluated right to left. Output choices: A 20101020; B 10202010; C 20102010; D 10201020.
Your answer
Answer & solution
Official answer: A
Step through it (13 steps)
Approach: Separate the calls that evaluate arguments from the calls inside f.
1. Derivation. Using the stipulated right-to-left argument evaluation, h(20) prints 20, then g(10) prints 10. Their return values bind x=10, y=20 in f. Its sequential statements then print10 and 20. With no separators the output is 20101020, option A. Right-to-left evaluation is an explicit premise here, not a portable C-language guarantee.
2. Explanation and checks. The event trace is h(20): print 20, return 20; g(10): print 10, return 10; enter f with x=10,y=20; g(x): print 10; h(y): print 20. Reversing evaluation order does not swap the formal parameters: the first argument still supplies x. The explicit right-to-left assumption applies to evaluating the argument expressions, not to reversing the two statements in the body of f.
In C, fX(char *a) sets char *b=a, executes while(*b) b++, then returns b−a as int. Which claims are true? A fX("abcd") returns; B with char c[]="abcd", fX(c) returns; C the function does not compile; D with char *c="abcd", fX(c) returns.
Select all that apply
Answer & solution
Official answer: A, B, D
Approach: Trace the pointer until the null terminator and distinguish reading a literal from modifying it.
1. Derivation. The pointer b advances until it reaches the terminating null byte and returns the element difference b−a, the string length. Each stated argument is a valid null-terminated four-character string, so each call returns 4. The function only reads characters; it does not modify string literals. Therefore A, B, D are true and the code is valid C. Pointer subtraction here is within the same array and the small result fits int.
2. Explanation and checks. The bytes at offsets 0,1,2,3 are a,b,c,d and are nonzero, so the loop advances four times. At offset 4 the terminating zero makes the condition false. Both pointers remain associated with the same character array, so subtraction gives four elements. The function never assigns through either pointer, and the supplied arguments are terminated, avoiding two common string errors. These are C examples; a stricter C++ string-literal type rule is not the language specified.
Options A, B and D print the string literal abcd between typographic quotation marks (”abcd”). These are read as ordinary ASCII string delimiters, and under that intended reading each call returns 4. The function definition itself contains no quotation marks and is valid C as printed; only the quote glyphs in the options, copied literally, would not form a C string literal.
Pointer distance versus pointed-to value difference
Pointers & Memory
Tap to enlarge
C code declares double a[2]={20.0,25.0}; sets p=a and q=p+1; and prints "%d,%d" with (int)(q−p), (int)(*q−*p). Which output? A 4,8; B 1,5; C 8,5; D 1,8.
Your answer
Answer & solution
Official answer: B
Approach: Evaluate the pointer expression and the dereferenced arithmetic expression separately.
1. Derivation. p points to a[0] and q=p+1 points to a[1]. Pointer subtraction counts array elements, not bytes, so q−p=1. The values differ by 25.0−20.0=5.0, cast to 5. The output is 1, 5, option B, independent of sizeof(double).
2. Explanation and checks. Adding one to a double pointer moves by the storage occupied by one double, but subtracting two double pointers converts the byte displacement back into an element count. Thus it is one regardless of the implementation’s double size. Dereferencing yields the numeric values 25.0 and 20.0, whose difference is exactly 5.0 here. The integer casts produce 1 and 5 for the two %d arguments; they do not turn the pointer difference into a byte distance.
The printed program uses typographic quotation marks and en dashes. Interpreting these as the intended ASCII C quotation marks and subtraction operators gives the stated answer B; copied literally, the printed characters do not form valid C tokens.
In C, funcp has static int x=1, then increments x and returns it. main declares separate int x,y, executes x=funcp(); y=funcp()+x; and prints x+y. What integer is printed?
Answer & solution
Official answer: 7
The static local x in funcp persists across calls. Its first call increments 1 to 2 and returns 2, assigned to main’s x. The second increments the same static value 2 to 3; main’s y becomes 3+2=5. Therefore main prints x+y=2+5=7. The local static and main’s x are distinct objects.
Teaching detail. A static local has block scope but static storage duration: its initialization occurs once, and the stored value survives a return from the function. It is not reinitialized to 1 at each invocation. Track the function's private x separately from main's x to avoid accidental overwriting: after the first call they both happen to equal 2, but the second call changes only the static variable to 3. main's previously stored x remains 2 and participates in both subsequent arithmetic expressions.
main calls f1(), f2(2), f3() in that order. f1 returns 1; f3 returns 5. f2(X) first calls f3(), then returns f1() if X==1, otherwise returns X*f2(X−1). Describe its activation tree and identify the matching source option.
Your answer
Answer & solution
Official answer: A
Main has three ordered children f1, f2(2), f3. The f2(2) activation first calls f3 and then recursively calls f2(1). That activation calls f3 and, because X=1, calls f1. Thus f2(2) has children f3, f2(1), and f2(1) has children f3, f1.
Teaching detail. An activation-tree node represents one invocation, not one distinct function name. The recursive f2 calls at arguments 2 and 1 therefore occupy different nodes. The ordered tree is main[f1, f2(2)[f3, f2(1)[f3,f1]], f3]. Returning a value does not create another activation, so multiplying by X adds no node. Likewise the final f3 called by main is a sibling of f2, not a descendant. This trace verifies both call nesting and left-to-right sibling order.
The binary tree has root 10, left child 5 with leaves 3,8, and right child 11 with right leaf 13. C function foo(NULL) returns 0; otherwise it evaluates retval=p->val+foo(p->left)+foo(p->right), prints retval, and returns retval. Find the output under the intended left-before-right evaluation, and explain the C-language caveat. Source options include C: 3 8 16 13 24 50.
Your answer
Answer & solution
Official answer: C
Our answer: C under left-before-right recursive evaluation; order not fixed by C
Each call returns its subtree sum and prints that sum after both child calls. The leaf sums are 3, 8, 13; the subtree rooted at 5 sums 16; that at 11 sums 24; the root sums 50. If the left recursive operand is evaluated before the right, the output is 3 8 16 13 24 50, official C. However C does not specify operand evaluation order for +. Evaluating the right subtree first can instead print13 24 3 8 16 50, and the two left leaves may also appear in either order. The printed order is therefore not portable as written; the final return value 50 is stable. Preserve the official answer with this missing evaluation-order assumption disclosed.
Teaching detail. For a node u, the return value obeys sum(u)=value(u)+sum(left)+sum(right), with sum(NULL)=0. The print is after both recursive returns, so children print their subtree totals before their parent prints. The left subtree total is 3+5+8=16; the right is 11+13=24; the root is 10+16+24=50. The parenthesization of additions does not impose an evaluation order on function-call operands in C. The key's ordering is therefore an intended traversal convention, not a portable consequence of the written expression.
Find the output of this ANSI C main body: int x=1,z[2]={10,11}; int *p=NULL; p=&x; *p=10; p=&z[1]; *(&z[0]+1)+=3; printf("%d, %d, %d\n",x,z[0],z[1]); return 0; (stdio.h included). A 1,10,11; B 1,10,14; C 10,14,11; D 10,10,14.
Your answer
Answer & solution
Official answer: D
Initially x=1 and z={10, 11}. Assigning 10 through p=&x changes x to 10. After p points to z[1], the expression *(&z[0]+1) denotes that same second element; adding 3 changes it to 14. z[0] stays 10. The printed values are 10, 10, 14, D.
Pointer reassignment changes what p refers to; it does not copy values between x and z. After *p=10, x remains 10 even after p moves. Array pointer arithmetic advances by one int, so &z[0]+1 is &z[1], not a byte address or z[0].
An ANSI C program initializes int a[3][3][3]={{1,2,3,4,5,6,7,8,9},{10,11,12,13,14,15,16,17,18},{19,20,21,22,23,24,25,26,27}}; int i=0,j=0,k=0; then for(i=0;i<3;i++){for(k=0;k<3;k++) printf("%d ",a[i][j][k]); printf("\n");}. Find the rows printed. A (1,2,3)/(10,11,12)/(19,20,21); B (1,4,7)/(10,13,16)/(19,22,25); C (1,2,3)/(4,5,6)/(7,8,9); D (1,2,3)/(13,14,15)/(25,26,27).
Your answer
Answer & solution
Official answer: A
The initializer fills the 3×3×3 array in row-major order with 1 through 27. The middle index is fixed at j=0, while i and k vary. The selected values are a[0][0][k]=1, 2, 3; a[1][0][k]=10, 11, 12; a[2][0][k]=19, 20, 21. Thus the output is option A.
The address/value formula for this initializer is a[i][j][k]=9i+3j+k+1. Since j never changes from zero, each outer iteration jumps nine values, while each inner iteration advances one. The newlines occur after the three k values, producing exactly three rows.
ANSI C uses char a='P',b='x'; char c=(a&b)+'*',d=(a|b)-'-',e=(a^b)+'+'; printf("%c %c %c\n",c,d,e). ASCII values P=80,x=120,*=42,−=45,+=43,z=122,K=75,S=83. Choose output: A z K S; B 122 75 83; C * − +; D P x +.
Your answer
Answer & solution
Official answer: A
Using the provided ASCII values, a=P=80 and b=x=120. a&b=80, so adding *=42 gives 122, character z. a|b=120, so subtracting -=45 gives 75, character K. ab=40, so adding +=43 gives 83, character S. Thus the output is z K S, option A.
Binary P=01010000 and x=01111000. AND keeps their shared 1 bits (01010000); OR combines them (01111000); XOR keeps differing bits (00101000). The arithmetic uses integer promotions, and the resulting 122,75,83 fit char. %c converts the codes to characters; %d would have printed numbers instead.
What happens in this ANSI C program? #include <stdio.h> int main(void){ int i,j,count; count=0; i=0; for(j=-3;j<=3;j++){ if((j>=0)&&(i++)) count=count+j; } count=count+i; printf("%d",count); return 0; } A fails compilation; B compiles and prints 10; C compiles and prints 8; D compiles and prints 13.
Your answer
Answer & solution
Official answer: B
Step through it (35 steps)
For j=−3,−2,−1 the left operand of && is false, so i++ is not evaluated. At j=0 the old i=0 makes the condition false, but increments i to 1. At j=1, 2, 3 the old i is nonzero, adding 1+2+3=6 while i reaches 4. The final addition gives count=6+4=10. Thus B. Short-circuiting and postincrement order are defined by C.
A compact trace (j, i after condition, count after body) is (−3,0,0),(−2,0,0),(−1,0,0),(0,1,0),(1,2,1),(2,3,3),(3,4,6). Postincrement yields the old value as the expression result, then changes i. The logical AND operator sequences and short-circuits its operands, so the first three iterations do not increment i at all. The final statement adds the final i=4 once, obtaining 10 without undefined unsequenced modifications.
ANSI C function: int SimpleFunction(int Y[],int n,int x){int total=Y[0],loopIndex; for(loopIndex=1;loopIndex<=n-1;loopIndex++) total=x*total+Y[loopIndex]; return total;} Array Z has ten elements, all equal to 1. Find SimpleFunction(Z,10,2).
Answer & solution
Official answer: 1023
The loop performs Horner evaluation. Starting at total=1, each of the nine iterations replaces total by 2*total+1. After k iterations total=2^(k+1)-1, so after nine iterations the result is 2^10-1=1023. All intermediate results are within even the minimum standard signed-int range.
The values after initialization and each iteration are 1,3,7,15,31,63,127,255,511,1023. An induction proves total after k loop iterations is 2k+1−1: base k=0 is 1, and 2(2k+1−1)+1=2k+2−1. More generally the function evaluates Y[0]xn−1+Y[1]xn−2+...+Y[n−1] in n−1 multiplications, which is Horner's method.
ANSI C declares int arr[4][5] and initializes arr[i][j]=10*i+j for 0≤i<4,0≤j<5. It prints *(arr[1]+9) with %d. Offered outputs: A 14; B 20; C 24; D 30. Explain the intended result and the language-standard issue.
Your answer
Answer & solution
Official answer: C
Our answer: C under intended flattening; undefined in strict C
The intended contiguous-address calculation begins at row1, column 0, linear index 5; advancing 9 integers reaches index 14=row2, column 4, whose initialized value is 24, C. However arr[1] decays to a pointer into the five-element row subarray. Adding9 goes beyond that array and its one-past position, so the expression has undefined behavior under C pointer-arithmetic rules. Contiguous storage of the outer array does not legalize this cross-row pointer arithmetic. The official C is retained as the intended exam answer, not a portable guarantee.
The intended memory layout has rows 0–4,10–14,20–24,30–34. The desired element is arr[2][4], which is a portable way to express it. Do not run this original expression and treat one observed compiler output as a proof of defined behavior. The official option describes the conventional exam address calculation only.
SomeFunction(x,y): if x==1 or y==1 return 1; if x==y return x; if x>y recurse on (x−y,y); if y>x recurse on (x,y−x). Find SomeFunction(15,255).
Answer & solution
Official answer: 15
Step through it (19 steps)
Each recursive step subtracts the smaller positive argument from the larger, preserving their gcd. Starting at(15, 255), repeated subtraction reaches(15, 15), which returns 15. Neither argument reaches 1 on this input.
The invariant gcd(x,y)=gcd(x,y−x) explains correctness, while decreasing x+y proves termination for positive integers. Here y successively becomes 240,225,…,30,15, after sixteen subtractions of 15, and the equality branch returns 15. A modulo-based Euclidean algorithm would skip these repeated subtraction calls.
C Node has int value; Node *next. Allocate head=boxE, set value=0. For index=1..3 allocate boxN, set boxE->next=boxN, boxN->value=index, boxE=boxN. Then for index=0..3 print head->value, assign head=head->next, and print head->value again. No final next initialization occurs. A five nodes created; B infinite loop; C missing return causes compile error; D uninitialized pointer dereferenced, possibly runtime error.
Your answer
Answer & solution
Official answer: D
The initial allocation plus three loop allocations create four nodes with values 0, 1, 2, 3. The final node’s next field is never initialized. The second loop advances head and dereferences it again each iteration; on the fourth iteration it reads that uninitialized next pointer and uses it for head->value. This is undefined behavior and may cause a runtime error, D. The loops themselves have bounded iteration counts.
Before the second loop, the chain is 0→1→2→3→uninitialized. The first three iterations safely advance to nodes 1,2,3 if allocation succeeds. The last iteration prints 3, then follows the indeterminate pointer and dereferences it. Initializing next to NULL alone would still leave the unconditional extra dereference invalid; correct traversal tests the pointer before using it. Allocation failure is another issue, not needed for the intended diagnosis.
foo(x,y,q): if x≤0 and y≤0 return q; if x≤0 return foo(x,y−q,q); if y≤0 return foo(x−q,y,q); otherwise return foo(x,y−q,q)+foo(x−q,y,q). What does printing foo(15,15,10) yield?
Answer & solution
Official answer: 60
Step through it (33 steps)
With q=10, each initial coordinate 15 requires two decrements to become nonpositive. When both remain positive the recursion branches on which coordinate decreases; once one is nonpositive only the other can decrease. Thus leaves correspond to the six interleavings of two x decrements and two y decrements, binomial(4, 2)=6. Each leaf returns 10, so the output is 60. There are no side effects across recursive calls, so unspecified operand evaluation order does not affect this sum.
Let F(i,j) denote the return with i,j remaining decrements needed. Interior recurrence F(i,j)=F(i−1,j)+F(i,j−1), with F(i,0)=F(0,j)=10. Hence F(1,1)=20, F(1,2)=F(2,1)=30, F(2,2)=60. The base is reached at −5, not necessarily exactly zero, because tests are nonpositive.
Find the output of this C program: #include <stdio.h> int main(void) { int a[4][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20}}; printf("%d\n", *(*(a+**a+2)+3)); return 0; }
Answer & solution
Official answer: 19
Step through it (6 steps)
Worked explanation
Track pointer types: in this expression a decays to a pointer to an array of five ints, so adding 1 advances by a whole row. *a denotes row zero, and a is its first integer, 1. Therefore a+a+2 is a+3. Dereferencing gives row three, which in the addition +3 decays to a pointer to its first int. Adding 3 selects its fourth entry and the outer dereference reads 19. Written with subscripts the expression is a[3][3], not a[0][6] or a linear six-element offset. Both row and column indices are valid.
Derivation and answer
Here a=a[0][0]=1. Thus a+a+2=a+3 points to the fourth row. Dereferencing that row and adding 3 selects a[3][3]=19. All pointer arithmetic stays within the relevant row/outer array, so the printed expression has the defined result 19.
Find fun2(5) on the first invocation of these C functions: int fun1(int n) { static int i=0; if(n>0) { ++i; fun1(n-1); } return i; } int fun2(int n) { static int i=0; if(n>0) { i=i+fun1(n); fun2(n-1); } return i; }
Answer & solution
Official answer: 55
Step through it (18 steps)
Worked explanation
Use different names u and v in the trace for fun1’s and fun2’s separate static variables. Static initialization occurs once, not on every recursive call. The successive outer fun1 calls add 5,4,3,2,1 to u, making return values 5,9,12,14,15. At the corresponding fun2 entries, v becomes 5,14,26,40,55. The final fun2(0) returns 55 without changing it. When earlier calls unwind, they all return the same current static v=55; ignored recursive return values are not added again. This is why neither the triangular sum 15 nor the sum 5+4+3+2+1 is the final answer.
Derivation and answer
The two static variables named i belong to different functions and persist across calls. Starting from their initial zeros, fun1(5) increments its i five times and returns 5; subsequent fun1(4), fun1(3), fun1(2), fun1(1) return 9, 12, 14, 15 respectively. fun2 adds those five results into its own static i, so it returns 5+9+12+14+15=55. The recursive return values ignored inside fun1/fun2 do not undo updates to static storage. This assumes the displayed call is the first invocation, as intended.
Find pp(3,4) for these C functions: int tob(int b,int *arr) { int i; for(i=0;b>0;i++) { if(b%2) arr[i]=1; else arr[i]=0; b=b/2; } return i; } int pp(int a,int b) { int arr[20]; int i,tot=1,ex,len; ex=a; len=tob(b,arr); for(i=0;i<len;i++) { if(arr[i]==1) tot=tot*ex; ex=ex*ex; } return tot; }
Answer & solution
Official answer: 81
Worked explanation
The first loop extracts bits from least significant to most significant. Its trace (b before division, stored bit) is (4,0),(2,0),(1,1), then b=0 and len=3. The second loop trace (i,bit,ex before squaring,tot after possible multiply) is (0,0,3,1),(1,0,9,1),(2,1,81,81). Squaring ex is outside the if, so it happens on all iterations; that placement is central. The final ex=6561 is not the returned variable. More generally the loop multiplies powers a2^i for the set bits of b, implementing exponentiation by repeated squaring, so pp(3,4)=34=81.
Derivation and answer
tob(4, arr) stores the low-to-high binary digits 0, 0, 1 and returns len=3. In pp, ex is successively 3, 9, 81. Only the third digit is 1, so tot changes from 1 to 81 then. The final squaring makes ex=6561 but does not change tot. Thus pp(3, 4) returns 81. All values here fit even a 16-bit signed int, so overflow does not alter this evaluation.
Tracing value parameters and successive assignments
Functions & Parameter Passing
Tap to enlarge
Function jumble(int x,int y) assigns x=2*x+y and returns x. Main initializes x=2,y=5, then executes y=jumble(y,x), then x=jumble(y,x), and finally prints main's x. Find the printed integer.
Answer & solution
Official answer: 26 to26
Our answer: 26
Method: keep the function's local parameter names separate from the caller's variables, and evaluate statements in sequence.
1. Initially main has (x,y)=(2,5). In y=jumble(y,x), the first argument is main's y=5 and the second is main's x=2. Inside the function, local (x,y) therefore starts as (5,2). 2. The function computes local x=2×5+2=12 and returns 12. C passes these integers by value, so changing the local x does not alter main's x. The assignment updates only main's y, leaving main at (2,12). 3. The second call, x=jumble(y,x), now passes (12,2). The returned value is 2×12+2=26, and the enclosing assignment stores it in main's x. 4. Main is now (26,12), so printing x displays 26. Reusing the function's parameter name x does not make it an alias of the caller's x.
Result: 26. The official range 26 to 26 accepts this exact value.
A C program initializes int arr[]={1,2,3,4,5,6,7,8,9,0,1,2,5}; and int *ip=arr+4; then prints ip[1] using the %d conversion. Find the integer displayed.
Answer & solution
Official answer: 6
Method: identify the pointer's base element, then apply C's definition of the subscript operator.
1. C array indices start at zero. Thus arr[0]=1, arr[1]=2, arr[2]=3, arr[3]=4, arr[4]=5, and arr[5]=6. “Index 4” denotes the fifth element, not the fourth. 2. In the expression arr+4, arr converts to a pointer to its first element, &arr[0]. Adding 4 to an int pointer advances it by four int elements, not by four bytes. Therefore ip=&arr[4], pointing at the value 5. 3. For a pointer p, C defines p[k] as *(p+k). Consequently ip[1]=*(ip+1): advance one more int from arr[4], then read the value at that location. 4. Substitute the pointer value explicitly: *(ip+1)=*((arr+4)+1)=*(arr+5)=arr[5]=6. 5. The access stays within the 13-element array and does not modify either ip or arr. The %d conversion prints the selected integer, followed by the newline specified in the program.
Result: 6. ip[0] would be 5, whereas ip[1] is 6; ip[1] is not the same as arr[1] because the two indexing expressions use different base pointers. No assumption about the byte size of int is needed.
For positive integer n, convert(n) executes: if(n<0) printf("%d",n); else { convert(n/2); printf("%d",n%2); }. Decide whether it prints ordinary binary and terminates (A), reversed binary and terminates (B), binary without terminating (C), or nothing without terminating (D).
Your answer
Answer & solution
Official answer: D
1. The stopping branch is n<0, not n==0. Integer division of a positive integer by 2 produces another nonnegative integer, so none of the recursive calls can enter the stopping branch. 2. Repeated halving eventually reaches zero. For example, an input 5 gives calls with arguments 5, 2, 1, 0. At zero the else branch calls convert(0/2), which is convert(0) again. 3. Each printf in the else branch occurs after the recursive call. Since the innermost call never returns normally, no pending printf is reached. The negative-argument printf is also unreachable. 4. Therefore the abstract recursion neither prints nor terminates: D. A real implementation has finite resources and typically exhausts its call stack, rather than literally running forever. The familiar binary-conversion algorithm would need a reachable base case; it cannot be substituted for the code actually supplied.
r() contains static int num=7 and returns num--. main executes for(r(); r(); r()) printf("%d",r()); then returns. Which displayed output is correct: A 41, B 52, C 63, D 630?
Your answer
Answer & solution
Official answer: B
Step through it (29 steps)
1. A static local variable is initialized once and keeps its value between calls. Post-decrement returns the old num and then reduces the stored value by one. 2. A for loop evaluates its initializer once, then repeatedly evaluates condition, body, and increment in that order. Calls in the initializer and increment still change num even though their returned values are discarded. 3. The initializer returns 7 and leaves num=6. The first condition returns 6, which is true, and leaves num=5. The body returns and prints 5, leaving num=4. The increment returns 4 and leaves num=3. 4. The second condition returns 3, so the body prints 2 and leaves num=1. The increment returns 1 and leaves num=0. The next condition returns 0, which is false, so there is no third body execution. 5. Only body calls print. No space or newline separates the two digits, so the displayed output is 52, option B. In particular, the zero used to stop the loop is never printed.
The C program initializes float sum=0.0,j=1.0,i=2.0 and repeats while(i/j>0.0625) { j=j+j; sum=sum+i/j; printf("%f\n",sum); }. How many times is sum printed?
Answer & solution
Official answer: 5
Step through it (26 steps)
1. The loop test is evaluated before doubling j. Variable i remains 2 throughout, while j doubles once per successful iteration. The threshold is 0.0625=1/16. 2. At successive tests, j is 1,2,4,8,16,32, giving i/j equal to 2,1,1/2,1/4,1/8,1/16. The first five values are strictly larger than 1/16; the sixth is equal and fails the > comparison. 3. Each of those five successful tests enters the body exactly once, executes one printf, and changes j to the next power of two. Therefore there are 5 prints. 4. As a check on operation order, the terms added inside the body use the already doubled j: 1,1/2,1/4,1/8,1/16. The printed sums are 1,1.5,1.75,1.875,1.9375, normally shown with six digits after the decimal by %f. 5. The test that stops execution produces no print. These powers of two and binary fractions are exactly representable in ordinary binary floating point, so rounding does not alter this stopping point.
In C, a={2,4,6,8,10}, sum=0, and int *b=a+4. For i=0 through 4, execute sum=sum+(*b-i)-*(b-i); then print sum as an integer. What is printed?
Answer & solution
Official answer: 10
Step through it (24 steps)
1. Pointer b is initialized to the final array element a[4]. No statement changes b, so *b remains 10 throughout the loop. 2. Distinguish the two expressions carefully. (*b-i) subtracts i from the value 10. By contrast, *(b-i) first moves the pointer i array positions backward and then reads a[4-i]. Pointer arithmetic counts int elements, not bytes. 3. For i=0,1,2,3,4, the first expression takes values 10,9,8,7,6. The second reads 10,8,6,4,2. Their differences are therefore 0,1,2,3,4. 4. Starting from zero, sum accumulates 0+1+2+3+4=10. Equivalently, a[4-i]=10−2i, so each summand is (10−i)−(10−2i)=i. 5. The output is 10 followed by a newline. All dereferences stay within a[0] through a[4]. The minus sign is subtraction, not a decrement of b, and confusing these operations would produce a different trace.
C declares struct Ournode { char x,y,z; }; initializes p={'1','0','a'+2}; sets q=&p; and prints printf("%c, %c", *((char*)q+1), *((char*)q+2)). Choices: A 0, c; B 0, a+2; C '0', 'a+2'; D '0', 'c'.
Your answer
Answer & solution
Official answer: A
Our answer: A under conventional layout and character encoding
Method
The cast occurs before pointer arithmetic: a char pointer advances by one byte, whereas adding 1 to a struct pointer would advance by a whole struct. Under the intended layout, offsets 1 and 2 select y and z. The expression 'a'+2 is evaluated numerically during initialization, not printed as source text. The %c conversion prints the represented character without surrounding quote marks. Keep the implementation assumptions below separate from the intended exam output.
Solution
With consecutive char members at byte offsets 0, 1, 2, the two dereferences read y and z. In an ASCII-compatible execution character set, y is the character 0 and z is c from a+2, giving 0, c, A. Strict ISO C permits internal struct padding and does not universally require contiguous alphabetic codes. The result therefore assumes the conventional padding-free char layout and character encoding used by the question.
Global int counter starts at 0. calc(a,b) increments counter, returns a*a*a if b==3, otherwise sets c=calc(a,b/3) and returns c*c*c. main calls calc(4,81), discards its return, then prints counter. Find the intended output.
Answer & solution
Official answer: 4
Our answer: 4 in intended call-count model; signed-overflow caveat
Method
Count activations on the descent separately from arithmetic on the return path. Calls occur at b=81,27,9,3; the last still increments counter before testing the base case. Unwinding produces mathematical values 4³,4⁹,4²⁷,4⁸¹. Already 4²⁷=2^54 exceeds a signed 32-bit range, and the final 2^162 exceeds signed 64-bit range. Thus counting gives the intended answer, but actual C execution is not guaranteed once signed overflow occurs.
Solution
The b arguments are 81, 27, 9, 3, so counter is incremented four times before the base return. The intended answer is 4. However the return computation then cubes repeatedly to 4^81=2^162, overflowing signed int on ordinary 32-bit or 64-bit implementations. Signed overflow is undefined behavior in C even if main discards the return value, so the printed result is not portable without sufficiently wide integer arithmetic or an explicit abstraction that ignores overflow.
In C, str1="Hi", str2="Bye". fun1(char *s1,char *s2) swaps its local pointer variables using a temporary. fun2(char **s1,char **s2) swaps *s1 and *s2. main calls fun1(str1,str2), prints both strings, calls fun2(&str1,&str2), then prints both. Choices A Hi Bye Bye Hi; B Hi Bye Hi Bye; C Bye Hi Hi Bye; D Bye Hi Bye Hi.
Your answer
Answer & solution
Official answer: A
Method
C passes arguments by value in both calls. In fun1 the copied values happen to be addresses of characters, so replacing those local copies cannot replace main’s variables. In fun2 the copied values are addresses of main’s pointer variables; dereferencing them selects those actual variables, which the assignments can modify. Neither routine edits the string literals. This distinction is between swapping pointed-to pointers and swapping local pointer copies, not between two language-level parameter-passing modes.
Solution
fun1 swaps only local copies of the pointer values, leaving main’s strings unchanged: Hi Bye. fun2 receives their addresses and swaps the actual pointer variables, so the second output is Bye Hi. The whole output is Hi Bye Bye Hi, A.
A 64-bit unsigned-long function initializes j=sum=0. It runs for(i=n;i>1;i=i/2) j++; then for(;j>1;j=j/2) sum++; returns sum. For n=2^40, choose A 4; B 5; C 6; D 40.
Your answer
Answer & solution
Official answer: B
Method
The first loop sees i=2^40,2^39,…,2 before stopping at i=1, so its body runs 40 times. The second loop then uses integer division: 40→20→10→5→2→1. It executes for the first five of these values, not for the final 1. The two loops are consecutive, not nested: multiplying their iteration counts would not describe the return value. The exponent in 2^40 is essential and can be lost in text extraction.
Solution
The first loop halves i until 1, performing 40 iterations, hence j=40. The second loop has j values 40, 20, 10, 5, 2 before stopping at 1, so sum=5, B.
Count(x,y) does nothing if y==1. Otherwise, if x!=1 it prints * and calls Count(x/2,y); if x==1 it calls Count(1024,y−1). Integers use truncating division. How many prints result from Count(1024,1024)?
Answer & solution
Official answer: 10230
Method
Separate the fast-changing variable x from the outer progress variable y. For each y>1, x halves ten times, since 1024=210. The x=1 call performs no print and starts the next y cycle with x reset. Values of y that produce prints are 1024 down through 2, a total of 1023, not 1024. The terminal y=1 call returns immediately, regardless of its x value. This counts executed print statements, not recursive invocations.
Solution
For a fixed y>1, x takes 1024, 512,..., 2, yielding 10 prints before reaching 1. Then y decreases by 1 and x resets to 1024. This occurs for y=1024, 1023,..., 2, namely 1023 rounds. At y=1 the function stops without printing. Therefore there are 10*1023=10230 prints in the abstract pseudocode model.
The printed C fragment is: typedef struct node { int data; node* next; } node; void join(node* m,node* n) { node* p=n; while(p->next != NULL) { p=p->next; } p->next=m; } Assume m and n point to valid NULL-terminated linked lists. A always appends m to n; B either null-pointer dereference or appends m to n; C always null-pointer dereference; D always appends n to m. The source typedef is retained literally, not silently repaired.
Your answer
Answer & solution
Official answer: B
Our answer: B under intended corrected C declaration
1. Trace the pointer, not the data fields: p starts at n, and each iteration follows the next link. For a nonempty terminating n list, the loop stops at its final node.
2. The assignment p->next=m connects that final node to the head of m. It therefore appends m to n, including the case m is empty.
3. An empty list can be represented by n=NULL; then even the first test p->next dereferences NULL. This prevents the “for all inputs” claim A. Intended B assumes a valid declaration and disjoint lists for an acyclic concatenation.
node* appears inside the typedef before node is declared as a typedef name. Standalone C needs struct node* next or an earlier forward typedef. This source defect is not repaired in the displayed code.
Printed C source: #include <stdio.h> int *assignval(int *x,int val) { *x=val; return x; } void main() { int *x=malloc(sizeof(int)); if(NULL==x) return; x=assignval(x,0); if(x) { x=(int *)malloc(sizeof(int)); if(NULL==x) return; x=assignval(x,10); } printf("%d\n",*x); free(x); } Choose A compiler error because malloc lacks a cast; B compiler error because NULL==x must be reversed; C compiles but may leave dangling pointer; D compiles but may leak memory. The missing stdlib.h and void main are literal source issues.
Your answer
Answer & solution
Official answer: D
Our answer: D under declared-library interpretation
1. Name the first allocated block A. If its allocation fails the function returns. Otherwise assignval(x,0) changes *x, not x: x still points to A and is nonnull.
2. Thus if(x) is entered even though the integer stored is zero. The second malloc result overwrites x, so no live variable retains A’s address.
3. If allocation B succeeds, printing/freeing uses B only. If it fails, the early return still does not free A. Either way after the second assignment A is leaked. This is intended D, subject to the source-declaration caveat below.
stdlib.h is omitted, so malloc/free lack their required declarations in modern C; void main is not a standard hosted entry point. The intended leak analysis assumes these routine issues are repaired, rather than endorsing option D’s literal “compiles successfully” wording.
Functions: void fun1(int n) { if(n==0)return; printf("%d",n); fun2(n-2); printf("%d",n); } void fun2(int n) { if(n==0)return; printf("%d",n); fun1(++n); printf("%d",n); } What does fun1(5) print? A 53423122233445; B 53423120112233; C 53423122132435; D 53423120213243. Assume declarations needed for mutual calls.
Your answer
Answer & solution
Official answer: A
Step through it (17 steps)
1. Record entry prints separately from return prints. fun1(5) prints 5 and calls fun2(3); that prints 3, increments its local n to 4, then calls fun1(4).
2. Continuing yields entries fun1(4),fun2(2),fun1(3),fun2(1),fun1(2),fun2(0). The zero call prints nothing. The nonzero entry sequence is 5,3,4,2,3,1,2.
3. Unwind in reverse: fun1(2) prints 2; fun2’s local n is now 2, so it prints 2; subsequent exits print 3,3,4,4,5. Entry string 5342312 plus exit string 2233445 gives 53423122233445, A.
int foo(int val) { int x=0; while(val>0) { x=x+foo(val--); } return val; } int bar(int val) { int x=0; while(val>0) { x=x+bar(val-1); } return val; } Classify foo(3),bar(3): A return 6,6; B infinite loop,abnormal termination; C abnormal termination,infinite loop; D both terminate abnormally.
Your answer
Answer & solution
Official answer: C
Our answer: C under ordinary finite-stack execution
1. Postdecrement in foo(val--) passes the old value, then decrements the caller’s local copy. Therefore foo(3) calls another foo(3), which calls another foo(3), without reaching a base case.
2. On conventional finite-stack execution, this unbounded recursion exhausts the stack and terminates abnormally. The exam uses that resource model; C does not prescribe a universal stack-overflow mechanism.
3. bar(val−1) passes a smaller value without modifying its caller. Calls descend 3,2,1,0, but bar(1) repeatedly calls bar(0) because its own val remains 1. It loops without return. Intended option C.
Source includes stdio.h and string.h. void printlength(char *s,char *t) { unsigned int c=0; int len=((strlen(s)-strlen(t))>c)?strlen(s):strlen(t); printf("%d\n",len); } void main() { char *x="abc"; char *y="defgh"; printlength(x,y); } The question explicitly says size_t, returned by strlen, is unsigned int. What is printed?
Answer & solution
Official answer: 3.0
Our answer: 3
1. strlen("abc")=3 and strlen("defgh")=5. The stipulated return type is unsigned int, so subtraction is unsigned rather than signed.
2. Let the unsigned modulus be U=UINT_MAX+1. Then 3−5 wraps to U−2, a large positive value, not signed −2. The comparison is against unsigned c=0 and is therefore true.
3. The conditional selects strlen(s)=3. Conversion of 3 to int is representable and printf prints 3. The surprising result comes from unsigned subtraction; the printed void main is a separate source portability issue.
void main is a nonstandard hosted-C entry point; the exam assumes an implementation accepting it.
#include <stdio.h> int total(int v) { static int count=0; while(v) { count+=v&1; v>>=1; } return count; } void main() { static int x=0; int i=5; for(;i>0;i--) { x=x+total(i); } printf("%d\n",x); } Find printed output.
Answer & solution
Official answer: 23.0
Our answer: 23
1. Inside total, v&1 extracts the low bit and v>>=1 removes it. The loop counts set bits, but count is static: its value persists across different calls.
2. Arguments are 5,4,3,2,1, with binary forms 101,100,11,10,1 and popcounts 2,1,2,1,1. Therefore total returns cumulative counts 2,3,5,6,7, rather than the individual popcounts.
3. main adds each returned value to its own x: 2, then 5,10,16,23. The final output is 23. Resetting count on each call would wrongly give 7.
void main is a nonstandard hosted-C entry point; the exam assumes an implementation accepting it.
Match C constructs P: static char var; Q: m=malloc(10); m=NULL; R: char *ptr[10]; S: register int var1; with i: sequence of locations storing addresses; ii: variable in data section; iii: request for CPU-register storage; iv: lost allocated memory that cannot be freed through the overwritten pointer. Options give (P,Q,R,S): A:(ii,iv,i,iii), B:(ii,i,iv,iii), C:(ii,iv,iii,i), D:(iii,iv,i,ii).
Your answer
Answer & solution
Official answer: A
1. P has static storage duration, conventionally placed in the static data/BSS region rather than a function-call stack, so P→ii. This is the exam's memory-layout description; the C language itself does not mandate a particular section name.
2. Q obtains a heap allocation and then overwrites its address with NULL. Assuming allocation succeeds and no other pointer retains the address, the allocation becomes unreachable and cannot be passed to free: Q→iv. Assigning NULL does not free it.
3. R declares an array of ten pointers to char, so its elements hold addresses: R→i. S uses register as a request/hint for register allocation, not a guarantee: S→iii. The complete mapping is A.
Consider C code: void printxy(int x,int y){ int *ptr; x=0; ptr=&x; y=*ptr; *ptr=1; printf("%d,%d",x,y); }. What does printxy(1,1) print? A:0,0. B:0,1. C:1,0. D:1,1.
Your answer
Answer & solution
Official answer: C
Step through it (10 steps)
1. At function entry the local parameter values are x=1,y=1. The assignment x=0 changes x, and ptr=&x makes ptr point to the storage occupied by x.
2. The expression *ptr reads that storage, currently 0, so y=*ptr copies 0 into y. This is a value copy, not a lasting connection between y and x.
3. The next statement *ptr=1 writes into x through the pointer. Now x=1 while y remains 0. The output is 1,0, option C. C function arguments are passed by value; the original call literals do not constrain these local assignments.
Unsigned integers x,y,q,r are used for division by repeated subtraction: while(r>=y){r=r-y; q=q+1;}. Which initial condition guarantees termination and final x==y*q+r? A:(q==r)&&(r==0). B:(x>0)&&(r==x)&&(y>0). C:(q==0)&&(r==x)&&(y>0). D:(q==0)&&(y>0).
Your answer
Answer & solution
Official answer: C
1. To preserve the intended division relation, use the invariant x=yq+r. Option C initializes q=0 and r=x, so the invariant holds before the loop. It also ensures y>0.
2. One iteration replaces r by r-y and q by q+1. Therefore y(q+1)+(r-y)=yq+r=x: the invariant is preserved. The guard r≥y prevents unsigned subtraction underflow.
3. Since y is positive, r decreases on every iteration and cannot decrease forever. At exit 0≤r<y, so q and r are the quotient and remainder. B leaves q unconstrained, D leaves r unconstrained, and A neither establishes the invariant for arbitrary x nor excludes y=0. C is the sufficient condition.
C code initializes array[]={3,5,1,4,6,2}, done=0. While done==0, set done=1; for i=0..4, if array[i]<array[i+1], swap them and set done=0; then for i=5..1 descending, if array[i]>array[i-1], swap them and set done=0. After the loop printf("%d",array[3]). swap exchanges the two addressed values. What is printed?
Answer & solution
Official answer: 3.0
Our answer: 3
Step through it (32 steps)
1. Both passes correct adjacent pairs toward descending order. In the forward pass a smaller value on the left is swapped right; in the backward pass a larger value on the right is swapped left. The initial forward pass changes [3,5,1,4,6,2] into [5,3,4,6,2,1].
2. Its backward pass produces [6,5,3,4,2,1]. In the next forward pass the remaining out-of-order pair 3,4 swaps, producing [6,5,4,3,2,1]; the backward pass then makes no changes.
3. Because a swap occurred, done remains 0 and one more full iteration verifies that no swaps are needed. Every strict adjacent inversion swap decreases a finite inversion count, so termination is justified. The final zero-based index 3 contains 3, which is printed. Index 3 means the fourth element, not the third.
C program fragment: int m=10; int n,n1; n=++m; n1=m++; n--; --n1; n-=n1; printf("%d",n);. What is printed?
Answer & solution
Official answer: 0.0
Our answer: 0
Step through it (12 steps)
1. Prefix increment changes the operand before producing its value. Thus n=++m first makes m=11 and then assigns n=11.
2. Postfix increment produces the old value and increments the operand by the end of the full expression. Hence n1=m++ assigns n1=11 and leaves m=12.
3. The separate statements n-- and --n1 reduce n and n1 to 10. Their prefix/postfix distinction does not matter when their expression values are discarded. Finally n-=n1 computes n=10-10=0, which is printed. These modifications occur in separate full expressions, so there is no unsequenced-increment ambiguity.
C program includes stdio.h and string.h, then executes char *c="GATECSIT2017"; char *p=c; printf("%d",(int)strlen(c+2[p]-6[p]-1));. What output is intended, and what caveat applies to the printed expression?
Answer & solution
Official answer: 2.0
Our answer: 2 under intended character-offset arithmetic; strict C undefined behavior
1. C defines a[b] as *(a+b), so 2[p]=p[2] and 6[p]=p[6]. In the string, these are T and I. Under ASCII-compatible character values, T-I-1=84-73-1=10.
2. If this integer offset is computed before pointer addition, c+10 points to the suffix "17" of GATECSIT2017. strlen then returns 2, and the explicit cast to int matches the %d format. This explains the official intended numerical answer.
3. Strictly, however, the printed additive expression is left-associative: ((c+2[p])-6[p])-1. Its first addition forms c+84, far outside the string object (12 characters plus its terminator). C does not allow that intermediate out-of-bounds pointer arithmetic, even if later subtraction would return to a valid offset. The printed program therefore has undefined behavior rather than a guaranteed output.
4. Writing c+(2[p]-6[p]-1) would avoid that intermediate-pointer problem under the intended encoding. The answer 2 additionally assumes an encoding giving the specified T-I difference; C does not require alphabetic characters to have ASCII codes. Preserve both the official intended answer and the strict-C/encoding caveat.
Given void f(int,short); and a main body declaring int i=100; short s=12; short *p=&s;, which expression can fill a call-site blank without a type-checking error? A: f(s,*s). B: i=f(i,s). C: f(i,*s). D: f(i,*p). The printed wrapper uses void main(); judge the candidate expressions.
Your answer
Answer & solution
Official answer: D
The function expects int and short and returns void. In D, i is int and *p is short, so f(i,*p) is well typed. A and C incorrectly dereference the nonpointer s; B tries assigning a void result to i. Thus D, evaluating the blank expression independently of the nonstandard void main wrapper.
The unary * operator requires a pointer operand. Since s is a short integer, *s is invalid regardless of the value 12 stored in it. By contrast p has type short*, so *p is a short lvalue compatible with f's second parameter. In B the arguments themselves are compatible, but f returns no value, so its call cannot supply an integer assignment value. Separate argument-type checking from return-value checking.
Find the printed value in this C program (stdio.h is included): void mystery(int *ptra,int *ptrb){int *temp;temp=ptrb;ptrb=ptra;ptra=temp;} int main(){int a=2016,b=0,c=4,d=42;mystery(&a,&b);if(a<c)mystery(&c,&a);mystery(&a,&d);printf("%d\n",a);}
Answer & solution
Official answer: 2016.0 : 2016.0
Our answer: 2016
mystery swaps only its local pointer parameters; it never writes through either pointer. All pointed-to integers remain unchanged and the conditional a<c is false. The printed a is 2016.
C passes the pointer values by value, producing local copies of the addresses. Changing which address ptra or ptrb contains does not modify a,b,c or d. To swap integers the function would need assignments through *ptra and *ptrb; to swap caller pointer variables it would need a different interface. After the first call a remains 2016, so 2016<4 is false. The final call likewise has no effect on a before printing.
Fill the loop condition so this C function returns the maximum array element for all n≥1: int max(int *p,int n){int a=0,b=n−1;while(____){if(p[a]<=p[b])a=a+1;else b=b−1;}return p[a];} A: a!=n. B: b!=0. C: b>(a+1). D: b!=a.
Your answer
Answer & solution
Official answer: D
At each iteration discard an endpoint no greater than the other: if p[a]≤p[b], advance a; otherwise decrement b. A maximum remains in the surviving interval. Continue until a=b, then return that sole survivor. Condition b!=a is D; stopping with two candidates is premature.
The invariant is that at least one maximum of the original array lies between indices a and b inclusive. Discarding the smaller endpoint preserves this invariant, including ties because the other equal value remains. Each step reduces b−a by 1, so termination occurs after n−1 iterations at a=b. For n=1 the correct loop runs zero times. Option C would stop with two values, potentially returning the smaller left one; A and B tie termination to fixed endpoints rather than convergence.
Find the printed sequence for count(3), where: void count(int n){static int d=1;printf("%d ",n);printf("%d ",d);d++;if(n>1)count(n−1);printf("%d ",d);} A:3 1 2 2 1 3 4 4 4. B:3 1 2 1 1 1 2 2 2. C:3 1 2 2 1 3 4. D:3 1 2 1 1 1 2. The printed main wrapper calls count(3); assume the usual printing declarations.
Your answer
Answer & solution
Official answer: A
Step through it (7 steps)
The static d is shared across recursive calls. Entry pairs are(3, 1),(2, 2),(1, 3); after the third increment d=4. Each of the three returning frames then prints 4. The complete sequence is 3 1 2 2 1 3 4 4 4, A. The snippet assumes normal printf declarations and acceptance of its void-main wrapper.
There is one static storage cell for d, not one copy per recursion frame. Trace entry: count(3) prints 3,1 and increments to 2; count(2) prints 2,2 and increments to 3; count(1) prints 1,3 and increments to 4. The base call skips recursion but still executes its final print. Returning callers also execute that final print and see the same shared 4. No decrement or new initialization happens during unwinding, which explains all three trailing 4s.
C-like code: void f(int* p,int m){m=m+5; *p=*p+m; return;} void main(){int i=5,j=10; f(&i,j); printf("%d",i+j);} Find the printed value under the intended ordinary integer execution.
Answer & solution
Official answer: 30.0 : 30.0
Our answer: 30
The value parameter m changes from 10 to 15 locally. Writing through p updates i from 5 to 20, while caller j stays 10. Hence i+j=30. Routine library declarations and the intended void-main extension are assumed.
Passing &i copies i’s address, not its value, into p. Dereferencing p consequently changes the caller’s i. Passing j copies 10 into the separate local variable m, so changing m cannot change j. The final addition is 20+10, not 20+15 or the original 5+10.
Code: int f(int*p,int n){if(n<=1)return 0; else return max(f(p+1,n-1),p[0]-p[1]);} int main(){int a[]={3,5,2,6,4};printf("%d",f(a,5));}. max returns the greater argument. Find the printed value.
Answer & solution
Official answer: 3.0 : 3.0
Our answer: 3
Step through it (13 steps)
The recurrence returns max(0, p[0]−p[1],..., p[n−2]−p[n−1]). For3, 5, 2, 6, 4 the adjacent differences are−2, 3,−4, 2; the maximum with 0 is 3.
Unwind from the end: the one-element suffix returns 0; suffix [6,4] returns max(0,2)=2; [2,6,4] returns max(2,−4)=2; [5,2,6,4] returns max(2,3)=3; the full array returns max(3,−2)=3. The function considers adjacent drops, not arbitrary pairs or absolute differences.
Find the printed integer. C code: void f1(int a,int b){int c;c=a;a=b;b=c;} void f2(int *a,int *b){int c;c=*a;*a=*b;*b=c;} int main(){int a=4,b=5,c=6;f1(a,b);f2(&b,&c);printf("%d",c-a-b);}. Assume required declarations.
Answer & solution
Official answer: -5
Our answer: −5
At f1 entry the parameters copy the caller's 4 and 5; swapping these copies leaves main's a,b,c at 4,5,6. In f2, the pointer parameters are also copied, but dereferencing them reaches main's b and c. Saving *a before overwriting prevents losing the original b. After the swap main has 4,6,5; subtraction is left-associative, so (5−4)−6=−5.
Solution: The value-parameter swap f1 changes only its local copies. The pointer-based f2 swaps caller b and c, giving a=4, b=6, c=5. Therefore c−a−b=−5, with routine declarations assumed.
Assume x address=2000 decimal and unsigned int occupies four bytes. Code: int main(){unsigned int x[4][3]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};printf("%u, %u, %u",x+3,*(x+3),*(x+2)+3);}. A 2036,2036,2036; B 2012,4,2204; C 2036,10,10; D 2012,4,6.
Your answer
Answer & solution
Official answer: A
Our answer: A under intended address display; literal printf has undefined behavior
x decays to a pointer to a whole three-element row, so adding 3 advances 3×12 bytes. Dereferencing that pointer produces a row array, which decays to its first-element pointer rather than the value 10. By contrast *(x+2)+3 adds three four-byte elements to the third row's base2024, again yielding numerical address 2036, now one past that row. These address calculations explain intended A only. Printing pointers with %u is a variadic type mismatch and undefined behavior; there is no guaranteed actual C output.
Solution: Each row occupies 3*4=12 bytes. x+3 points to the fourth row at 2000+36=2036; *(x+3) decays to that row’s first element at 2036. *(x+2)+3 is the valid one-past pointer of the third row, also numerically 2036 under the stated layout. Thus the intended address triple is 2036, 2036, 2036, A. However all three arguments are pointers while %u requires unsigned int; this variadic format mismatch is undefined behavior in C. A conforming address display uses %p with each pointer cast to void*, whose textual format is implementation-defined. The omitted stdio declaration is another standalone-code caveat.
For positive integers x,y: q:=0; r:=x; while r≥y do {r:=r−y; q:=q+1}. Which postcondition holds? A r=qx+y and r<y; B x=qy+r and r<y; C y=qx+r and 0<r<y; D q+1<r−y and y>0.
Your answer
Answer & solution
Official answer: B
Prove the invariant x=qy+r by initialization and preservation: (q+1)y+(r−y)=qy+r. The guard ensures subtracting y never makes r negative. Since positive y decreases r at every step, the loop terminates and the false guard gives r<y. Therefore q is the integer quotient and r the remainder with 0≤r<y. A remainder may be zero, so a strict lower bound such as that in C would be wrong.
Solution: Initially q=0, r=x, so x=qy+r. Each iteration replaces r by r−y and q by q+1, preserving that invariant. Positive y decreases nonnegative r on every iteration; termination gives 0≤r<y. Hence the listed postcondition x=qy+r and r<y is B; the full invariant also supplies the nonnegative lower bound.
C function foo(char*a){if(*a && *a!=' '){foo(a+1); putchar(*a); }}. Output for string “ABCD EFGH”? A ABCD EFGH; B ABCD; C HGFE DCBA; D DCBA.
Your answer
Answer & solution
Official answer: D
Recursion stops at the first space without advancing beyond it. Each earlier character is printed only after its recursive call returns, reversing ABCD and producing DCBA, D.
The condition stops recursion when the pointer reaches either the terminator or the first space. Starting at A, the function calls on B, C, D and then the space, where it returns without printing. Printing occurs after each recursive call, so unwinding emits D, C, B, A. No invocation reaches EFGH. Had putchar preceded the recursive call, the first word would print forward instead.
Let F1=1 and Fn=1+sum(Fk F(n−k), k=1..n−1). Then F2=2, F3=5, F4=15, F5=1+15+10+10+15=51. Values fit int in this call.
The function’s accumulator begins at 1 on every call. Its recurrence is F(n)=1+Σ F(k)F(n−k), with F(1)=1. Compute bottom-up: F(2)=1+1=2; F(3)=1+2+2=5; F(4)=1+5+4+5=15. For n=5, the four products are 15, 10, 10, 15, and the initial 1 makes 51. Forgetting the initial 1 would incorrectly substitute a different recurrence.
A global int pointer A and global stkTop coexist with stkFunc’s static int size=0, stkTop=0. Opcode −1 sets size=val; opcode 0 pushes A[stkTop++]=val when stkTop<size; the default returns A[--stkTop] if nonempty, otherwise −1. main points A at B[20], sets global stkTop=−1, sets capacity 10, pushes 5 then 10, and prints stkFunc(1, 0)+stkFunc(1, 0). Find the output.
Answer & solution
Official answer: 15
The function-local static stkTop starts at 0 and shadows the global stkTop, so assigning the global variable−1 does not affect the stack. After configuring size 10 and pushing 5 then 10, the two pops return 10 and 5 in whichever operand-evaluation order is chosen. Their sum is 15. Although the + operands have unspecified order, the two function executions are indeterminately sequenced rather than interleaving their bodies; this is not the direct unsequenced-increment case.
Track the function-local static top, not the global of the same name. Capacity initialization leaves the local top at 0. Pushing 5 writes B[0] and changes it to 1; pushing 10 writes B[1] and changes it to 2. The two calls then return 10 and 5, in whichever operand-call order is chosen. Their sum is 15. A function’s static local persists between calls, and lexical scope makes it hide the global stkTop, so setting that global to −1 does not underflow this stack.
What does this C program print? #include <stdio.h> int main() { char s1[7]="1234", *p; p=s1+2; *p='0'; printf("%s",s1); } The assigned character is digit '0', not the null character '\0'. Options: (A) 12; (B) 120400; (C) 1204; (D) 1034.
Your answer
Answer & solution
Official answer: C
Step through it (8 steps)
1. Initially the character array begins with 1,2,3,4 followed by a null terminator. Pointer arithmetic advances by characters, so s1+2 selects the third stored character. The assignment changes that position only; printf with %s stops at the unchanged original terminator.
2. p points to s1[2]. Assigning character'0' replaces digit 3, not the terminating null byte. The string becomes 1204 followed by its original terminator, so C.
Consider this recursive C function: void get(int n) { if(n<1) return; get(n-1); get(n-3); printf("%d",n); } If main invokes get(6), how many total invocations of get occur before control returns to main, including the initial invocation and calls that immediately return? Options: (A) 15; (B) 25; (C) 35; (D) 45.
Your answer
Answer & solution
Official answer: B
Step through it (24 steps)
1. For n≤0 the invocation still counts once even though it immediately returns. Starting with C(−2)=C(−1)=C(0)=1, repeatedly apply the recurrence upward; omitting the base-case calls would count printed values rather than invocations.
2. Count every invocation including base cases and the initial call. C(n)=1 for n<1 and C(n)=1+C(n−1)+C(n−3) otherwise. Thus C1=3, C2=5, C3=7, C4=11, C5=17, C6=25. Answer B.
Determine the output of this C program, using the standard function-call sequencing model: #include <stdio.h> int f1(void); int f2(void); int f3(void); int x=10; int main() { int x=1; x += f1()+f2()+f3()+f2(); printf("%d",x); return 0; } int f1() { int x=25; x++; return x; } int f2() { static int x=50; x++; return x; } int f3() { x *= 10; return x; }
Answer & solution
Official answer: 230
1. There are three distinct variables named x: global x, main’s automatic x, and f2’s persistent static x; f1 additionally creates its own automatic x on entry. Name lookup selects the nearest declaration, so f3 alone modifies the global. The two f2 returns may exchange evaluation order, but their sum stays 103.
2. Main’s local x starts 1. f1 returns 26 from its own automatic x; the two f2 calls return 51 and 52 from one static x in either order; f3 multiplies global 10 by 10 and returns 100. Sum1+26+51+52+100=230. Function executions are indeterminately sequenced, so unspecified operand order does not change the sum or cause overlapping unsequenced increments.
What is the intended printed output of this C program? Also distinguish that output from its portability limitation. #include <stdio.h> int main() { static int a[]={10,20,30,40,50}; static int *p[]={a,a+3,a+4,a+1,a+2}; int **ptr=p; ptr++; printf("%d%d",ptr-p,**ptr); } There is no separator between the two decimal conversions.
Answer & solution
Official answer: 140
Our answer: 140 under compatible printf type convention
1. After ptr++, ptr=p+1, so ptr−p=1 and **ptr=*(a+3)=40.
2. The adjacent decimal conversions produce 140. Pointer subtraction has type ptrdiff_t, which need not be int; %d is portable only when its promoted type is int. Otherwise the format mismatch is undefined behavior. Use %td for ptr−p, or cast this known-small difference to int, to guarantee the intended display.
Y is a one-dimensional array of size n and X a C two-dimensional n×n array, with 2≤n≤10. Each segment starts with Y[i]=0 and X[i][j]=i+j. All X elements lie in the same main-memory page frame. Segment 1: for(i=0;i<n;i++) Y[i]+=X[0][i]; Segment 2: for(i=0;i<n;i++) Y[i]+=X[i][0]; Assess S1: final Y contents are identical; S2: X elements accessed in segment 1 are contiguous in memory; S3: X elements accessed in segment 2 are contiguous. Options: (A) S2 only; (B) S3 only; (C) S1 and S2 only; (D) S1 and S3 only.
Your answer
Answer & solution
Official answer: C
1. Both loops add i to initially zero Y[i], because X[0][i]=0+i and X[i][0]=i+0.
2. In C row-major storage, X[0][i] traverses consecutive elements, whereas X[i][0] advances by n elements for n≥2. Being in one page does not make those column elements adjacent. Thus S1, S2, C.
How many times is printf executed in this C program? #include <stdio.h> int main() { int i,j,k=0; j=2*3/4+2.0/5+8/5; k-=--j; for(i=0;i<5;i++) { switch(i+k) { case 1: case 2: printf("\n%d",i+k); case 3: printf("\n%d",i+k); default: printf("\n%d",i+k); } } return 0; } There are no break statements.
Answer & solution
Official answer: 10
1. Integer division gives 2*3/4=1 and 8/5=1; adding 2.0/5 produces 2.4, converted to int j=2.
2. Then k-=--j sets j=1 and k=−1. For i=0, 1, 2, 3, 4 the switch values are−1, 0, 1, 2, 3. With no breaks, the numbers of printf executions are 1, 1, 3, 3, 2, totaling 10. Case1 falls into case2 without printing itself.
Consider the C program with stdio included: main(){ int i; int *pi=&i; scanf("%d",pi); printf("%d\n",i+5); }. Which statement is true? A: Compilation fails. B: A runtime error occurs. C: It prints five more than the address of i. D: It prints five more than the integer entered. Interpret the legacy main declaration under the intended historical C convention.
Your answer
Answer & solution
Official answer: D
Our answer: D under the intended C execution assumptions
1. Method and setup. The address operator makes pi point to the existing integer object i. scanf requires precisely such a destination pointer for %d, so this is equivalent to passing &i. printf subsequently evaluates the integer expression i+5; it does not use the pointer’s numeric address.
2. Work through the result and its assumptions. pi is a valid pointer to i, so a successful scanf conversion stores the entered integer in i and printf displays i+5, D. Assume representable input and no signed overflow; the source also uses legacy implicit-int main syntax rather than modern int main(void). These routine source conventions matter for literal compilation.
In C, MyX(int *E,unsigned int size) first sets Y=0 and adds every E[i] to Y. It then loops i=0..size−1 and j=i..size−1, initializes Z=0, sums E[k] for k=i..j, and replaces Y by Z if Z>Y. It returns Y. What does it return? A: Maximum sum of a contiguous subarray. B: Maximum element in a subarray. C: Sum of maximum elements of all subarrays. D: Sum of all array elements.
Your answer
Answer & solution
Official answer: A
1. Method and setup. Each ordered index pair i≤j describes one nonempty contiguous subarray. The innermost loop computes its sum from scratch. The running variable Y retains the largest sum seen; initializing it to the whole-array sum ensures a valid candidate even when every entry is negative, unlike initializing the final maximum to zero.
2. Work through the result and its assumptions. Y starts as the sum of the whole array, itself a valid nonempty contiguous subarray. Every pair i≤j is then enumerated and Z sums exactly E[i..j]; Y is replaced whenever this sum is larger. Thus the final Y is the maximum nonempty subarray sum, A. This assumes a nonempty valid array, representable indices and no signed arithmetic overflow; for an empty array the routine returns 0.
For the C function int func(int num){int count=0; while(num){count++; num>>=1;} return count;}, find func(435).
Answer & solution
Official answer: 9
1. Set up the reasoning. The input is positive, so repeated right shifts discard low bits until the most significant 1 has also been shifted away. The return value is binary length, not population count.
2. Derive the result. For positive num, each right shift divides by 2 and discards the remainder. The sequence 435, 217, 108, 54, 27, 13, 6, 3, 1 has 9 nonzero values before 0, so the loop returns 9.
3. Check the interpretation. Since 28≤435<29, exactly nine shifts are needed. This gives a compact independent check of the explicit sequence and avoids confusing shifts-to-zero with the number of set bits.
Unsigned int variables n and p are used in C to compute p=n choose 3. For large n, which statement is most likely to work correctly? A p=n*(n-1)*(n-2)/6; B p=n*(n-1)/2*(n-2)/3; C p=n*(n-1)/3*(n-2)/2; D p=n*(n-1)*(n-2)/6.0;
Your answer
Answer & solution
Official answer: B
1. Set up the reasoning. Consider two separate hazards: overflow of intermediate unsigned products and truncation by integer division. Adjacent integers n and n-1 always have an even product, permitting an exact early division by two.
2. Derive the result. B divides the always-even product n(n−1) by 2 before multiplying by n−2, reducing intermediate magnitude without truncation. The final division by 3 is exact for the integer binomial product. A and D form the larger full product before division, while C may divide n(n−1) by 3 prematurely, truncating when n≡2 mod3. B is less overflow-prone, not guaranteed correct for arbitrarily large unsigned n; even its intermediate can wrap.
3. Check the interpretation. Multiplication and division associate left to right. The final floating divisor in D does not retroactively convert preceding integer products to floating point. B mitigates risk but cannot guarantee correctness for every representable n or for results too large to fit p.
Consider the printed function double f(double x){if(abs(x*x-3)<0.01) return x; else return f(x/2+1.5/x);}. Give a value q, to two decimal places, such that f(q) returns q. Preserve the printed abs rather than silently replacing it with fabs.
Answer & solution
Official answer: 1.72 to 1.74
Our answer: 1.73 in the intended real-absolute-value model
1. Set up the reasoning. For immediate return under the intended mathematical absolute-value interpretation, test whether the chosen two-decimal q satisfies abs(q²-3)<0.01. The recursive expression is a Newton update for a square root, but no iteration is needed if the starting value already passes.
2. Derive the result. For mathematical absolute value, immediate return requires|q²−3|<.01. q=1.73 gives q²=2.9929 and error.0071<.01, so it returns immediately (as does−1.73). The positive value is within the official range. Literal C abs takes an int: with declarations in scope, the double difference is truncated before testing, so every q with|q²−3|<1 returns immediately, including 1.50. The source should use fabs for floating absolute value if that is intended; the negative solution is also valid without a positivity restriction. Official1.72 to 1.74 is retained, with these distinct semantics explicit.
3. Check the interpretation. The distinction between mathematical absolute value and C's integer abs is substantive. The latter converts the double argument to int before testing, broadening immediate-return values. Also the source does not require q positive, so -1.73 is mathematically valid despite the positive official interval; retain the existing discrepancy.
For C function int f(int j){static int i=50; int k; if(i==j){printf("something"); k=f(i); return 0;} else return 0;}, which is true? A returns 0 for every j; B prints something for every j; C returns 0 for j=50; D exhausts the runtime stack or loops indefinitely when j=50.
Your answer
Answer & solution
Official answer: D
1. Set up the reasoning. The static variable is initialized once and never modified. Split the trace into j≠50, which returns immediately, and j=50, which repeats exactly the same call state.
2. Derive the result. The static i remains 50 across calls. If j≠50, the function immediately returns 0. If j=50, it prints and calls f(50) again without changing the condition; no call reaches its following return. With ordinary recursive frames the stack is exhausted; an optimization eliminating redundant frames could instead run indefinitely. Thus D, assuming normal successful output operations.
3. Check the interpretation. The return statement after the recursive call is unreachable unless that call returns, and the recursion has no changing measure or base case for 50. Optimizations may affect stack growth but do not create the missing termination condition.
For an n×n matrix A, execute C=100; for i=1,…,n and j=1,…,n execute Temp=A[i][j]+C; A[i][j]=A[j][i]; A[j][i]=Temp−C. Then print A in row order. What is printed? A original A; B transpose of A; C upper-diagonal entries increased by 100 and lower-diagonal entries decreased by 100; D none of these.
Your answer
Answer & solution
Official answer: A
Step 1: Track one iteration with old values u=A[i][j] and v=A[j][i]. Temp=u+100, then the assignments store v and (u+100)−100=u, so the body swaps the two entries. Step 2: For i≠j, both index pairs (i,j) and (j,i) occur in the complete nested loops. The second swap undoes the first. A diagonal entry is swapped with itself. Step 3: Consequently every entry finishes unchanged, A. This reasoning uses exact arithmetic or assumes no problematic overflow in adding and subtracting C.
For a supplied X, find the minimum number of arithmetic operations needed to evaluate P(X)=X⁵+4X³+6X+5 using only one temporary variable. This is a numerical-answer question.
Answer & solution
Official answer: 7
Our answer: At most 6; official 7 is not minimal under algebraic refactoring
Step 1: Sparse Horner form is X((X²+4)X²+6)+5. An evaluation recomputing X² with one temporary can use seven additions/multiplications, explaining the official key 7. Step 2: However, expand X[(X²+2)²+2]+5: the square is X⁴+4X²+4, so multiplying X(X⁴+4X²+6)+5 gives the same polynomial. Step 3: Execute t=X*X; t=t+2; t=t*t; t=t+2; t=t*X; t=t+5. This uses only X and one temporary t, with three multiplications and three additions. Step 4: Six operations suffice, so 7 cannot be the unrestricted minimum. This is an upper-bound counterexample, not a proof that 6 is globally minimal. Keep the official answer and the open discrepancy separate; no unstated ban on algebraic refactoring has been supplied.
A sorted ascending array listA has n>0 entries. ProcessArray sets i=0,j=n−1, then repeatedly sets k=(i+j)/2 using integer division; if x≤listA[k], sets j=k−1; independently, if listA[k]≤x, sets i=k+1; repeats while i≤j. Afterward returns k if listA[k]==x, else −1. Which is correct? A absent x causes an infinite loop; B this is binary search; C it always finds the maximum; D it returns −1 even when x is present.
Your answer
Answer & solution
Official answer: B
Step 1: If x is smaller than the midpoint, only the first comparison succeeds, eliminating the midpoint and upper half. If x is larger, only the second succeeds, eliminating the lower half. Each unsuccessful iteration strictly shrinks the candidate interval. Step 2: If x equals the midpoint, both independent tests succeed: j=k−1 and i=k+1. The loop terminates immediately, and the final equality test returns the matching k. Step 3: Therefore it implements binary search, B, including for duplicates where any matching index suffices. Assume a valid nonempty sorted array and arithmetic without overflow in i+j.
For integer n, unknown initializes k=0; for i=n/2 through n inclusive, for j=2 while j≤n doubling each time, it adds n/2 to k; finally returns k. Choose growth of returned value: AΘ(n²), BΘ(n²log n), CΘ(n³), DΘ(n³log n). Integer divisions truncate; asymptotics use no-overflow mathematical arithmetic.
Your answer
Answer & solution
Official answer: B
The outer loop runs Θ(n) times and the doubling inner index takes Θ(log n) iterations for each. Each iteration adds a value Θ(n) to the accumulator. Thus the returned value is Θ(n² log n), B. The number of loop-body executions, and hence the usual unit-cost running time, is only Θ(n log n); the question asks for the value returned. This asymptotic calculation uses mathematical integers or assumes no integer overflow, rather than literal fixed-width C behavior for arbitrarily large n.
There are n−floor(n/2)+1 outer iterations. For n≥2 the inner values are 2, 4,…, 2^floor(log2 n), so there are floor(log2 n) inner iterations each time. Each contributes floor(n/2), giving the exact mathematical-integer value [n−floor(n/2)+1]floor(log2 n)floor(n/2). Multiplying these three orders gives Θ(n²log n). A running-time answer would omit the magnitude added per iteration and would be a different question.
Which replacement maps expose cascading substitutions
Arrays & Strings
Tap to enlarge
Code loops i=0…4 then j=0…2, and if A[i]==oldc[j] immediately sets A[i]=newc[j], without breaking. Maps are 1 abc→dab;2 cde→bcd;3 bca→cda;4 abc→bac. Testing every 5-character input from{a, b, c, d, e}, how many maps expose its replacement flaw? A1, B2, C3, D4.
Your answer
Answer & solution
Official answer: B
The defect is that the inner loop continues after a match, so a replacement character can match a later oldc entry and be replaced again. In case 1 (abc→dab), a becomes d, b becomes a after the a-entry has already been passed, and c becomes b after the b-entry has been passed. No input character cascades. In case 2 (cde→bcd), each replacement is absent from the remaining suffix of oldc, so again no character cascades. In case 3 (bca→cda), an original b first becomes c and then becomes d; the intended one-step result is c. In case 4 (abc→bac), an original a first becomes b and then becomes a; the intended result is b. Exhaustive length-five input testing includes strings containing b and a, respectively, so exactly cases 3 and 4 can reveal the flaw. That is two cases, option B. The five-character array need not be NUL-terminated because the code accesses exactly its five given elements.
The intended specification performs one replacement based on the original character, whereas the code repeatedly tests the updated character. For each map, inspect whether a replacement equals an oldc entry at a later j. Only later entries matter: a match with an earlier entry is never revisited. Map3 has b→c with c later, and map 4 has a→b with b later. Maps 1and2 only map backward or outside the remaining entries, so no repeated substitution can occur. Exhaustive input testing guarantees witnesses containing the affected characters.
Use the same nested replacement loops and four maps 1 abc→dab;2 cde→bcd;3 bca→cda;4 abc→bac. For input abcde specifically, which expose the flaw? A none; B2 only; C3and4; D4 only.
Your answer
Answer & solution
Official answer: C
Apply each map once to each original character to obtain the intended result, then compare with the procedure’s sequential replacements. For input abcde, case 1 has intended and actual output dabde. Case 2 has intended and actual output abbcd. Case 3 should produce acdde, but its b is changed twice, b→c→d, producing addde. Case 4 should produce bacde, but its initial a is changed twice, a→b→a, producing aacde. Therefore cases 3 and 4 expose the defect, option C.
The fixed input contains every candidate letter once, including both b and a that trigger the two flaws. In map 3 the intended b→c is followed by an unintended c→d, changing the second character from expected c to d. In map 4 the intended a→b is followed by unintended b→a, undoing that substitution. Comparing complete strings confirms the discrepancy rather than relying merely on the presence of an intermediate match. Cases 1and2remain unaffected.
What will be the output of the following C program segment?
char inChar = ‘A’ ; switch ( inChar ) { case ‘A’ : printf (“Choice A\ n”) ; case ‘B’ : case ‘C’ : printf (“Choice B”) ; case ‘D’ : case ‘E’ : default : printf ( “ No Choice” ) ; } (A) No Choice (B) Choice A (C) Choice A Choice B No Choice (D) Program gives no output as it is erroneous
Your answer
Answer & solution
Official answer: Marks to All
Our answer: C under intended newline interpretation
If the first printf is interpreted as the intended standard newline escape \n, execution enters case A and falls through every following label because there is no break. It prints Choice A, a newline, then Choice B and No Choice, matching C. The printed source visibly separates the backslash and n in the first string; taking backslash-space literally is not the standard newline escape and does not justify an unconditional portable-output answer. The official key awards Marks to All. This is an independently observed printing/interpretation concern, not a claim about the authority’s reason.
Check: Switch labels are entry points, not implicit stopping points. After executing the case-A printf, the empty B label passes through to C’s printf; D and E are also empty, so execution reaches default’s printf before leaving the switch.
Common code (source-era C syntax retained): int a,b,c=0; void prtFun(void); main() { static int a=1; /* Line 1 */ prtFun(); a+=1; prtFun(); printf(" \n %d %d ",a,b); } void prtFun(void) { static int a=2; /* Line 2 */ int b=1; a+=++b; printf(" \n %d %d ",a,b); } What three output pairs are printed? (A) (3,1);(4,1);(4,2) (B) (4,2);(6,1);(6,1) (C) (4,2);(6,2);(2,0) (D) (3,1);(5,2);(5,2).
Your answer
Answer & solution
Official answer: C
Assume the snippet is meant as a storage-duration exercise with an appropriate printf declaration and a valid int main(void) supplied; the printed implicit-int main and omitted stdio declaration are not a portable modern-C complete program. The file-scope b has static storage and starts at 0. In prtFun, local b starts at 1 on each call and ++b makes it 2. Its static a starts at 2 once, then becomes 4 on the first call and 6 on the second, printing (4, 2) and (6, 2). The separate main-local a starts at 1 and is incremented to 2; main sees global b=0 and prints (2, 0). Hence C.
Check: There are three different a objects and two different b objects. The function-local a persists across calls but is not main’s a; function-local b shadows global b and never changes it. Keeping an object-by-object trace avoids incorrectly carrying local b back into main.
Common code (source-era C syntax retained): int a,b,c=0; void prtFun(void); main() { static int a=1; /* Line 1 */ prtFun(); a+=1; prtFun(); printf(" \n %d %d ",a,b); } void prtFun(void) { static int a=2; /* Line 2 */ int b=1; a+=++b; printf(" \n %d %d ",a,b); } Replace Line 1 by auto int a=1; and Line 2 by register int a=2;. What three pairs are printed? (A) (3,1);(4,1);(4,2) (B) (4,2);(6,1);(6,1) (C) (4,2);(6,2);(2,0) (D) (4,2);(4,2);(2,0).
Your answer
Answer & solution
Official answer: D
Under the same intended valid-declarations assumptions as the preceding common-data question, changing main-local a to auto does not change its lifetime within this single invocation of main: it still becomes 2. Changing prtFun-local a to register gives it automatic storage duration, not persistent storage; each call initializes it to 2. Each call also initializes local b=1, increments b to 2, adds 2 to a, and prints (4, 2). Finally main prints its a=2 and the zero-initialized global b=0. The three output pairs are (4, 2), (4, 2), (2, 0), option D. register does not guarantee physical register allocation.
Check: Storage-class changes affect persistence, not lexical scope. Both modified declarations still shadow the same globals. The register local is recreated on every invocation, so it cannot retain the first call’s value 4 when the second call starts.
What does this literal C fragment print? The initial capital in Char is as printed. Char c[] = "GATE2011"; char *p = c; printf("%s", p + p[3] - p[1]);
(A) GATE2011 (B) E2011 (C) 2011 (D) 011
Your answer
Answer & solution
Official answer: C
Our answer: C only under intended offset arithmetic; literal C is not well-defined
Using ASCII arithmetic, E−A=4, so the intended pointer is c+4 and the intended suffix is 2011, C. But p+p[3]−p[1] associates as (p+p[3])−p[1]. Its first pointer operation forms p+69 in ASCII, far beyond the 9-byte array, causing undefined behavior before the subtraction returns to offset 4. The source also capitalizes Char, which is not the C keyword char unless separately defined. Replacing Char with char and writing p+(p[3]−p[1]) repairs the intended calculation, still with an explicit character-encoding assumption. The official result is not a guarantee of the literal fragment.
Index the intended string: c[0]='G', c[1]='A', c[2]='T', c[3]='E', c[4]='2', c[5]='0', c[6]='1', c[7]='1', c[8]='\0'. A valid pointer to c[4] makes %s print characters until c[8], producing 2011. This explains the examiner's arithmetic but must not erase the separate language-law issues in the literal source. Pointer arithmetic has validity requirements at every intermediate operation, not only at the final address.
Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(345,10) return?
(A) 345 (B) 12 (C) 5 (D) 3
Your answer
Answer & solution
Official answer: B
Step through it (9 steps)
For positive n and base r>1, n%r is the final base-r digit and integer division n/r removes it. The recursive calls therefore sum the digits. With n=345 and r=10, the return is 5+4+3+0=12, option B.
Unroll the calls: foo(345,10)=5+foo(34,10); foo(34,10)=4+foo(3,10); foo(3,10)=3+foo(0,10); the last call returns 0. The call stack then returns 3,7,12 in reverse order. It does not reconstruct the original number because no place-value multiplications are used, and it does not stop after the first remainder. The base case is essential to terminate after all digits have been consumed.
Consider unsigned int foo(unsigned int n, unsigned int r) { if (n>0) return ((n%r)+foo(n/r,r)); else return 0; }. What does foo(513,2) return?
(A) 9 (B) 8 (C) 5 (D) 2
Your answer
Answer & solution
Official answer: D
Step through it (23 steps)
The function sums the base-r digits of n. Since 513=512+1=29+1, its binary representation is 1000000001 and has two 1 bits. Consequently foo(513, 2)=2, option D. All intermediate recursive divisions are unsigned integer divisions and terminate at zero.
The successive n values are 513,256,128,64,32,16,8,4,2,1,0. Remainders modulo 2 are 1 at n=513 and n=1 and zero at every other positive step. Summing them produces 2. The exponent 9 tells where the highest bit lies, not how many set bits there are; similarly, the number of recursive positive calls is 10, not the return value. The function counts ones for base 2 because binary digits can only be zero or one.
What does this C program print? #include <stdio.h> void f(int *p, int *q) { p=q; *p=2; } int i=0, j=1; int main(void) { f(&i,&j); printf("%d %d\n",i,j); return 0; } Options: (A) 2 2; (B) 2 1; (C) 0 1; (D) 0 2.
Your answer
Answer & solution
Answer: D (no official key was published)
Initially i=0 and j=1. The local parameter assignment p=q redirects p to j, without altering i or the caller’s pointer arguments. Then *p=2 writes j=2. The printed values are 0 2, option D.
C passes the pointer values by value. At entry p contains &i and q contains &j; p=q copies &j into the local pointer p. It does not copy j into i. The later dereference acts on the new pointee j. Distinguish p=q, which redirects a pointer, from *p=*q, which would copy an integer.
What value does this C program print? #include <stdio.h> int f(int *a,int n) { if(n<=0) return 0; else if(*a%2==0) return *a+f(a+1,n-1); else return *a-f(a+1,n-1); } int main(void) { int a[]={12,7,13,4,11,6}; printf("%d",f(a,6)); return 0; } Options: (A) −9; (B) 5; (C) 15; (D) 19.
Your answer
Answer & solution
Answer: C (no official key was published)
Step through it (17 steps)
Evaluate from the last array element backward. The empty suffix returns 0; f([6])=6; f([11,6])=11−6=5; f([4,11,6])=4+5=9; f([13,4,11,6])=13−9=4; f([7,13,4,11,6])=7−4=3; finally 12+3=15. The function tests each current element’s parity, not its index. Printed value 15, C.
The recurrence is not a flat alternating sum of the original elements: subtraction applies to the entire recursively computed suffix. Parentheses make the evaluation explicit: 12+(7−(13−(4+(11−6))))=15. Pointer arithmetic a+1 advances to the next integer and n−1 shrinks the remaining array; the parity test examines the value *a at each call.
Complete this C function so it moves the last node of a singly linked list to the front and returns the new head. typedef struct node { int value; struct node *next; } Node; Node *move_to_front(Node *head) { Node *p,*q; if(head==NULL || head->next==NULL) return head; q=NULL; p=head; while(p->next!=NULL) { q=p; p=p->next; } /* BLANK */ return head; } Options: (A) q=NULL; p->next=head; head=p;; (B) q->next=NULL; head=p; p->next=head;; (C) head=p; p->next=q; q->next=NULL;; (D) q->next=NULL; p->next=head; head=p;.
Your answer
Answer & solution
Answer: D (no official key was published)
At loop exit p points to the last node and q to its predecessor. First set q->next=NULL to detach p, then p->next=head to link p before the old first node, and finally head=p. This is option D. Updating head before p->next would lose the old head and can create a self-loop; the early return already handles lists shorter than two nodes.
For A→B→C, the loop ends with p=C and q=B. Detach B→C, point C→A and set head=C, obtaining C→A→B→NULL. Choice A only clears the local variable q and leaves B linked to C, producing a cycle. Choice B makes C point to itself. Choice C loses the old head connection by linking the last node to its predecessor instead.
C function fun(n, f_p) sets *f_p=1 and returns 1 if n≤1; otherwise t=fun(n−1, f_p), f=t+*f_p, *f_p=t, then returns f. main initializes x=15 and prints fun(5, &x). Choices A 6; B 8; C 14; D 15.
Your answer
Answer & solution
Answer: B (no official key was published)
Step through it (13 steps)
At n=1 the function returns 1 and stores 1 through the pointer, overwriting the initial 15. For n=2, 3, 4, 5 the pairs(returned value, stored value) are(2, 1), (3, 2), (5, 3), (8, 5). The printed return value is 8, B.
The pointer is shared through all recursive calls, so its value must be tracked alongside the returned integer. The deepest call overwrites 15 with 1; thus 15 contributes nothing to the result. Each unwinding step returns the sum of the previous two Fibonacci-like values and stores the former return value for the next step. A trace gives n1:(1, 1), n2:(2, 1), n3:(3, 2), n4:(5, 3), n5:(8, 5). printf uses the returned 8, not the final stored 5.
Which (x,y,z) makes a=4 in the C expression a=(x>y)?((x>z)?x:z):((y>z)?y:z)?
(A) (3,4,2) (B) (6,5,3) (C) (6,3,5) (D) (5,4,5)
Your answer
Answer & solution
Answer: A (no official key was published)
1. If x>y, the expression selects the larger of x and z. Otherwise it selects the larger of y and z. Thus a=max(x,y,z). 2. The maxima for A,B,C,D are respectively 4,6,6,5. 3. Only A yields 4. Equality in a comparison does not change the selected maximum value.
What does this historical C program print? int f(int x, int *py, int **ppz) { int y,z; **ppz += 1; z=*ppz; *py += 2; y=*py; x += 3; return x+y+z; } void main() { int c,*b,**a; c=4; b=&c; a=&b; printf("%d",f(c,b,a)); }
(A) 18 (B) 19 (C) 21 (D) 22
Your answer
Answer & solution
Answer: B only if z=*ppz is repaired to z=**ppz; no portable numeric answer as printed (no official key was published)
1. The scan prints **ppz += 1; z = *ppz; with only one dereference in the assignment to z. Since ppz has type int **, *ppz is an int * rather than the integer value of c. Assigning that pointer to int z violates the standard C simple-assignment constraints and requires a diagnostic. Consequently the printed program has no portable numeric answer among the options; accepting it as an extension does not make z equal to 5. 2. If the apparent typo is explicitly repaired to z = **ppz, the intended alias trace is: x starts as a separate copy 4; **ppz += 1 makes c=5 and z=5; *py += 2 makes c=7 and y=7; x += 3 makes x=7. The sum is then 7+7+5=19, option B only for that repaired program. 3. The source also uses historical void main() and omits the stdio declaration. Those conventions do not remove the single-dereference defect. The derived answer is therefore conditional: B applies only after the stated repair, and no listed portable answer is justified for the printed code. No official key is available.
Fill ?1 and ?2 so this historical C program reverses a newline-terminated input string. void reverse(void) { int c; if (?1) reverse(); ?2 } main() { printf("Enter Text"); printf("\n"); reverse(); printf("\n"); }
1. Each invocation must read and retain its own character: ((c=getchar()) != '\n'). Recurse only for a non-newline character, then putchar(c) while unwinding. 2. This prints the input characters in reverse, option D. As written, the base invocation also prints the terminating newline before the reversed characters; main then prints a newline afterward. 3. A and B use getchar instead of output; C tests an uninitialized c. The source uses legacy implicit-int main; interpret the algorithm under its historical C conventions.
Consider these C functions, assuming valid array bounds and the intended unit-cost arithmetic model: int f1(int n) { if(n==0 || n==1) return n; else return 2*f1(n-1)+3*f1(n-2); } int f2(int n) { int i; int X[N],Y[N],Z[N]; X[0]=Y[0]=Z[0]=0; X[1]=1; Y[1]=2; Z[1]=3; for(i=2;i<=n;i++) { X[i]=Y[i-1]+Z[i-2]; Y[i]=2*X[i]; Z[i]=3*X[i]; } return X[n]; } What values do f1(8) and f2(8) return?
(A) 1661 and 1640 (B) 59 and 59 (C) 1640 and 1640 (D) 1640 and 1661
Your answer
Answer & solution
Answer: C (no official key was published)
1. Both functions implement a0=0, a1=1, an=2a(n−1)+3a(n−2). In f2, Y[i]=2X[i] and Z[i]=3X[i], including the initialized indices, so X has exactly that recurrence. 2. Values a2 through a8 are 2,7,20,61,182,547,1640. Thus both return 1640, option C, assuming N≥9. 3. Equivalently an=(3^n−(−1)^n)/4.
This erroneous historical C binary-search function uses integer division: 1. f(int Y[10], int x) { 2. int i,j,k; 3. i=0; j=9; 4. do { 5. k=(i+j)/2; 6. if(Y[k]<x) i=k; else j=k; 7. } while((Y[k]!=x) && (i<j)); 8. if(Y[k]==x) printf("x is in the array"); 9. else printf("x is not in the array"); 10. } For which input does it fail?
(A) Y=[1,2,3,4,5,6,7,8,9,10], x<10 (B) Y=[1,3,5,7,9,11,13,15,17,19], x<1 (C) Y=[2,2,2,2,2,2,2,2,2,2], x>2 (D) Y=[2,4,6,8,10,12,14,16,18,20], 2<x<20 and x even
Your answer
Answer & solution
Answer: C (no official key was published)
1. With all entries equal to 2 and x>2, every comparison takes i=k. The interval evolves (i,j)=(0,9)→(4,9)→(6,9)→(7,9)→(8,9), then k remains 8 forever. 2. Y[k]≠x and i<j both stay true, so the program fails to terminate, option C. For A, all integer keys below 10 that are present (1 through 9) can be found and keys below 1 terminate as absent; B also shrinks j to zero and terminates absent; D contains only present even values strictly between its endpoints.
This erroneous historical C binary-search function uses integer division: 1. f(int Y[10], int x) { 2. int i,j,k; 3. i=0; j=9; 4. do { 5. k=(i+j)/2; 6. if(Y[k]<x) i=k; else j=k; 7. } while((Y[k]!=x) && (i<j)); 8. if(Y[k]==x) printf("x is in the array"); 9. else printf("x is not in the array"); 10. } Which correction makes the program work properly?
(A) Replace line 6 with if(Y[k]<x) i=k+1; else j=k−1; (B) Replace line 6 with if(Y[k]<x) i=k−1; else j=k+1; (C) Replace line 6 with if(Y[k]<=x) i=k; else j=k; (D) Replace line 7 with } while((Y[k]==x) && (i<j));
Your answer
Answer & solution
Answer: No fully correct option; A repairs the update but is incomplete (no official key was published)
1. Option A changes the bounds to i=k+1 or j=k−1, removing the nonprogress bug in Q84. But line 7 still tests i<j, so it can stop before examining a remaining singleton. Counterexample: Y=[1,2,3,4,5,6,7,8,9,10], x=4. 2. With A, k=4 gives j=3; k=1 gives i=2; k=2 gives i=3. Now i=j=3, so the loop exits and wrongly reports absent because its last examined value was Y[2]=3. A complete repair also changes the continuation bound to i<=j (while retaining the found test), or rewrites the usual while(i<=j) search. 3. B expands bounds, C still stalls on many absent keys, and D continues on equality instead of inequality. Thus A is the likely intended correction, but none alone makes the displayed program generally correct.
Consider the C fragment: int j, n; j = 1; while (j <= n) j = j * 2; For n>0, how many comparisons are made during execution? The printed choices are below; note the distinction between successful comparisons and the final failing test. Options: (A) ceil(log₂ n)+1 (B) n (C) ceil(log₂ n) (D) floor(log₂ n)+1
Your answer
Answer & solution
Answer: floor(log2 n)+2 including the final failed test; no exact listed option (no official key was published)
1. Approach. Let k=floor(log₂ n). The successful tests use j=20 through 2k. Then the loop tests 2k+1 once and fails. Check n=1 as a quick boundary example: two tests, one iteration.
2. Derivation and interpretation. Assume n is supplied positive and arithmetic does not overflow. The loop condition is tested with j=1,2,4,...,2^floor(log2 n), all successful, then once more at 2^(floor(log2 n)+1), which fails. Thus body executions and successful comparisons number floor(log2 n)+1, but all comparisons number floor(log2 n)+2. Option D counts successful tests/body executions only. The fragment declares n without assigning it; the question’s n>0 premise must supply its value, and literal fixed-width C may also overflow for large n. No official key is inferred.
What is f(5) for the following C function? int f(int n) { static int r=0; if(n<=0) return 1; if(n>3) { r=n; return f(n-2)+2; } return f(n-1)+r; } Options: (A) 5 (B) 7 (C) 9 (D) 18
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (11 steps)
1. Approach. The static r is one persistent shared object, not a fresh zero-initialized local for each recursive call. Record the single assignment r=5 before unwinding the recursion.
2. Derivation and interpretation. The static variable r is shared by all activations. In f(5), r becomes 5, and the return expression is f(3)+2. Calls f(3), f(2), and f(1) each recurse with n−1 and add the unchanged r=5. The base f(0)=1. Hence f(1)=6, f(2)=11, f(3)=16, and f(5)=18 (D). No smaller activation changes r, so operand evaluation order does not affect this particular call.
For positive integer n, the C fragment is: for (i=n,j=0; i>0; i/=2,j+=i); . Here i,j,n are integer variables and the loop body is empty. Which is the asymptotic value of j after termination, rather than the running time? Options: (A) Θ(log n) (B) Θ(√n) (C) Θ(n) (D) Θ(n log n)
Your answer
Answer & solution
Answer: C (no official key was published)
1. The update uses the comma operator: first integer-divide i by 2, then add the new i to j. For positive n, j=floor(n/2)+floor(n/4)+...=n−popcount(n).
2. It is at least floor(n/2) and less than n, hence Θ(n), C. This is the value accumulated, not the Θ(log n) iteration count.
3. Its value remains below n, so no positive signed overflow is needed when n is representable.
4. Teaching check: For n=13 the updates add 6,3,1,0, yielding j=10 even though there are only four iterations. Generally the sum lies between floor(n/2) and n, which supplies matching linear bounds without needing the exact popcount identity.
Sorted integer arrays a[0…n−1],b[0…m−1] have positive lengths. Array c has capacity n+m. Execute: i=j=k=0; while (i<n && j<m) { if (a[i]<b[j]) c[k++]=a[i++]; else c[k++]=b[j++]; } Which printed postcondition is valid? I: if i=n, then j<m, k=n+j−1, and a[n−1]<b[j]. II: if j=m, then i<n, k=m+i−1, and b[m−1]≤a[i]. The −1 terms are retained exactly as reproduced in both sources. Options: (A) Only I (B) Only II (C) Either I or II, but not both (D) Neither I nor II
Your answer
Answer & solution
Answer: D (no official key was published)
1. The loop starts i=j=k=0. Each iteration increments exactly one of i,j and also k, preserving k=i+j.
2. At termination, if i=n then j<m and k=n+j; the final extraction from a implies a[n−1]<b[j]. If j=m then i<n and k=m+i; the final extraction from b implies b[m−1]≤a[i].
3. Both printed assertions instead give k one less than these values. Hence neither assertion is correct: D.
4. This uses positive array lengths and defined array accesses, as intended by the example.
6. Teaching check: Initially k=i+j=0. Every loop iteration increments k and exactly one of i,j, so k=i+j remains true. At exit, replacing i by n or j by m yields k=n+j or k=m+i, directly contradicting the printed −1 regardless of the final comparison.
C code: void swap(int *px,int *py) { *px=*px-*py; *py=*px+*py; *px=*py-*px; } Statements: S1 compilation error; S2 may cause a segmentation fault for some arguments; S3 correctly swaps for all pointers to accessible integers; S4 correctly swaps for some but not all valid input pointers; S5 may add/subtract integers and pointers. Which statements are intended to be true? Options: (A) S1 (B) S2 and S3 (C) S2 and S4 (D) S2 and S5
Your answer
Answer & solution
Answer: C (no official key was published)
1. The code uses *px=*px−*py; *py=*px+*py; *px=*py−*px. For distinct valid integer objects and arithmetic without signed overflow, initial values x,y become x−y,y then x−y,x then y,x, correctly swapping.
2. If px=py, the first assignment zeroes the shared object and the result is not a swap unless it was zero. Invalid pointers may cause a segmentation fault.
3. Thus S2 and S4 are the intended statements: C. No pointer arithmetic occurs, and there is no intrinsic compilation error.
4. Signed overflow is an additional undefined-behavior limitation even with distinct accessible objects.
5. Teaching check: Aliasing is decisive: if px and py point to the same nonzero integer, the first subtraction writes zero and destroys the original value. With distinct valid cells the algebraic swap works only when each intermediate signed operation is representable. Dereferencing an invalid pointer is a further separate risk.
Interpret C declaration int (*f)(int *). A function taking int* and returning int; B function taking int and returning int*; C pointer to function taking int* and returning int; D function taking int* and returning a function pointer.
Your answer
Answer & solution
Answer: C (no official key was published)
In int (*f)(int *), the parentheses make f a pointer. Its target is a function taking one int-pointer argument and returning int. Thus C; it is not a function returning a pointer.
Read outward from f. The parentheses bind *f before the following parameter list, so f is a pointer. Its pointed-to object is a function whose parameter is int* and whose return type, written at the left, is int. Without parentheses, int *f(int*) would instead declare a function returning int*. That binding distinction gives C.
void foo(int n, int sum){int k=0, j=0;if(n==0)return;k=n%10;j=n/10;sum=sum+k;foo(j, sum);printf("%d,", k);} main sets a=2048, sum=0; calls foo(a, sum); prints sum with newline. Output? A8, 4, 0, 2, 14; B8, 4, 0, 2, 0; C2, 0, 4, 8, 14; D2, 0, 4, 8, 0.
Your answer
Answer & solution
Answer: D (no official key was published)
Step through it (13 steps)
Calls peel off digits 8, 4, 0, 2, but each prints only after its recursive child returns. Thus the visible digits are 2, 0, 4, 8. The sum parameter is passed by value, so main’s sum stays 0. Assuming the usual stdio declaration, the output is 2, 0, 4, 8, 0 followed by a newline, option D; the commas come from the inner printf format.
Each call stores its own last digit k before recursively processing the remaining prefix. Because printing occurs after the child returns, digits appear from most significant to least:2, 0, 4, 8. The sum variable is a by-value local parameter, so changes do not propagate back into main’s sum. Main consequently appends 0, giving D. This question combines recursive output order with parameter passing, not a digit-sum algorithm that returns its result.
Program declares double foo(double) before main. main declares double da, db, obtains da through omitted input code, and assigns db=foo(da). Later definition double foo(double a){return a;}. If the initial declaration is removed, choose A no diagnostic; B harmless warnings; C type-mismatch warnings with unintended results; D compile errors. Distinguish standard-required diagnostic from implementation severity.
Your answer
Answer & solution
Answer: D in ordinary C compilation (no official key was published)
Without the declaration, foo is called before its type is known. Modern C requires a declaration; historical implicit-int rules would assume an int-returning function, which conflicts with the later double-returning definition. A diagnostic is therefore required, and conventional compilers reject the conflicting types, D. C specifies required diagnostics rather than an absolute distinction between a warning and a fatal error, so exact compiler behavior depends on mode/extensions. The commented input of da is understood as omitted input code, as the prompt intends.
The early declaration tells the compiler that the call returns double. Removing it means a modern C compiler encounters an undeclared function call; older implicit-int conventions instead assume int, which conflicts with the later double definition. A diagnostic is required, and ordinary compiler modes reject the conflicting types, making D the conventional choice. The standard does not mandate the user-interface label warning versus error, so that distinction remains qualified.
Line 3 of historical C code is fro(I=0, I<N, I++); inside int main(){int I, N; ...}. During object-module creation is the response A no compilation error; B lexical error only; C syntactic error only; D both? Preserve the printed identifier fro and comma-separated expressions, not a repaired for loop.
Your answer
Answer & solution
Answer: A under C90; modern C needs a diagnostic (no official key was published)
The printed line is fro(I=0, I<N, I++); with commas, not semicolons. Lexically fro is a valid identifier, and syntactically this is a function call with three arguments, not a for statement. Under the historical C90 implicit-function-declaration rule, an object module can be produced, so A is the intended compilation-stage answer; a missing definition may fail at link time. In C99 and later the undeclared function requires a diagnostic, but this is not a lexical or grammar error of the kind offered. The argument side effects also give undefined runtime behavior under C90 because I is modified more than once without an intervening sequence point; no runtime result is asserted. The paper preserve fro and commas.
The lexer accepts fro as an ordinary identifier. The grammar accepts the following parentheses as a function call whose three arguments are I=0, I<N, I++. Thus misspelling for does not by itself create a lexical or grammar error. Older C allowed an implicit function declaration; an undefined fro may be discovered later by the linker. Modern C requires a diagnostic for the undeclared function, and runtime side effects are separately problematic. The intended old compilation-stage answer must not be presented as portable modern C.
Consider this C function: void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } To exchange caller variables x and y, which statement is correct? Options: (A) Call swap(x,y) (B) Call swap(&x,&y) (C) swap(x,y) cannot be used because it returns no value (D) swap(x,y) cannot be used because its parameters are passed by value
Your answer
Answer & solution
Answer: D (no official key was published)
1. The function receives local copies a and b. Swapping those copies does not modify the caller’s x,y, so D.
2. A void function can modify caller objects through pointers, but this function’s parameters are int, not int*, and calling it with addresses does not repair its body.
3. Teaching check: Trace x=3,y=8: entry makes local a=3,b=8; the body leaves a=8,b=3, but x=3,y=8. A correct pointer-based version would take int *a,int *b and exchange *a,*b. A return value is not essential for that alternative.
For the first invocation of this C function, what does f(1) return? int f(int n) { static int i=1; if(n>=5) return n; n=n+i; i++; return f(n); } Options: (A) 5 (B) 6 (C) 7 (D) 8
Your answer
Answer & solution
Answer: C (no official key was published)
Step through it (6 steps)
1. On the first call, n=1,i=1; the update yields n=2,i=2. The next call yields n=4,i=3, then n=7,i=4.
2. Since7≥5, that call returns7 and the result propagates back, C. This assumes f(1) is the first call, since static i persists across calls.
3. Teaching check: Static storage is initialized once, not once per recursive activation. The entry states (n,i) are (1,1),(2,2),(4,3),(7,4). Replacing static i with an ordinary local initialized to 1 would produce a different trace and return 5.
An input nonnegative integer has original digits d1 d2 … dm. The fragment is: int n, rev; /* n contains the input */ rev=0; while(n>0) { rev=rev*10+n%10; n=n/10; } Which invariant holds after iteration i? Assume integer division and no overflow; digit strings denote numeric values. Options: (A) n=d1…d_(m−i) AND rev=d_m d_(m−1)…d_(m−i+1) (B) n=d_(m−i+1)…d_(m−1)d_m OR rev=d_(m−i)…d2 d1 (C) n≠rev (D) n=d1 d2…d_m OR rev=d_m…d2 d1
Your answer
Answer & solution
Answer: A (no official key was published)
1. After i iterations, n is the original prefix d1...dm−i, and rev is the processed suffix in reverse order dm dm−1...dm−i+1, A. Each step removes n’s final digit and appends it to rev.
2. The notation describes numeric digit values, so leading zeros in the reversed suffix do not change the value; assume the input is supplied nonnegative and the reversed value fits int.
3. Teaching check: For input 1234, successive (n,rev) pairs are (123,4),(12,43),(1,432),(0,4321). This verifies both halves of the invariant simultaneously. An OR condition that merely describes the initial or final arrangement does not express the state after every iteration.
What is printed by this C fragment? Assume appropriate declarations/includes for i, strlen and printf. char p[20]; char *s="string"; int length=strlen(s); for(i=0;i<length;i++) p[i]=s[length-i]; printf("%s",p); The %s format follows GFG. GateForum visibly prints a malformed alternate format rather than %s. Options: (A) gnirts (B) string (C) gnirt (D) No output is printed
Your answer
Answer & solution
Answer: D under the displayed intended C fragment (no official key was published)
1. The source length is 6. At i=0, p[0]=s[length−0]=s[6], which is the string terminator.
2. Consequently printf with %s sees an empty string immediately, regardless of later copied characters, and prints nothing, D. This uses the paper’s %s format and assumes surrounding declarations/includes for i and the library functions.
4. Teaching check: The source string positions are 0:s,1:t,2:r,3:i,4:n,5:g,6:\0. The very first assignment copies position 6 into p[0].
What does this C-style fragment compute for positive integers x,y? m=x; n=y; while(m!=n) { if(m>n) m=m-n; else n=n-m; } printf("%d",n); GFG option A is division by repeated subtraction; GateForum prints x+y instead. Options: (A) x/y by repeated subtraction (B) x mod y by repeated subtraction (C) Greatest common divisor of x,y (D) Least common multiple of x,y
Your answer
Answer & solution
Answer: C (no official key was published)
1. For positive x,y, each iteration replaces the larger of m,n by its difference with the smaller. This preserves gcd(m,n), keeps both positive, and strictly decreases m+n until m=n.
2. The printed common value is gcd(x,y). This is not ordinary repeated subtraction for division: the roles of the two operands change.
3. Teaching check: For x=12,y=8, the pairs evolve (12,8)→(4,8)→(4,4), so the answer is 4. Every common divisor is preserved by subtracting one operand from the other. The positive decreasing sum proves termination, completing both partial correctness and progress.
For large positive integer y, what does this C function approximate? float f(float x, int y) { float p, s; int i; for(s=1,p=1,i=1; i<y; i++){p*=x/i; s+=p;} return s; } A. x^y; B. e^x; C. ln(1+x); D. x^x.
Your answer
Answer & solution
Answer: B (no official key was published)
1. The recurrence for p is p₀=1 and pᵢ=pᵢ₋₁x/i. Induction gives pᵢ=xⁱ/i!. The accumulator includes the initial term 1, so it contains exactly y terms, not y+1. Comparing with the Taylor expansion eˣ=1+x+x²/2!+⋯ identifies the limit.
2. Initially p=1 and s=1. On iteration i, p is multiplied by x/i, so it becomes xi/i!, which is added to s. The returned value is the truncated series sum from i=0 to y−1 of xi/i!, approaching ex for fixed x as y increases. Thus B in the mathematical arithmetic model; finite floating-point range/roundoff can limit the actual approximation.
Given int *A[10], B[10][10]; consider I. A[2], II. A[2][3], III. B[1], IV. B[2][3]. Which expressions can be left-hand sides of assignments without compile-time errors, assuming type-compatible right-hand sides? A. I, II and IV only; B. II, III and IV only; C. II and IV only; D. IV only.
Your answer
Answer & solution
Answer: A (no official key was published)
1. Resolve the declarations before considering assignment: A[i] has type int*, while B[i] has array type int[10]. Applying another subscript dereferences an element and yields int in either case. Arrays are not modifiable lvalues, but pointer objects and int objects are. No actual dereference safety can be inferred from these declarations alone.
2. A is an array of 10 pointers to int. A[2] is an assignable pointer object, and A[2][3] is an assignable int lvalue if the pointer identifies suitable storage. B[2][3] is likewise an int lvalue. B[1] is an array row and cannot be assigned as a whole in C. Thus I,II,IV, option A, with type-compatible right-hand sides; compile-time validity does not establish safe runtime initialization.
In this C fragment j,k,n,TwoLog_n are integers, A is an integer array and n≥3. GFG defines TwoLog_n=2 floor(log2 n); GateForum instead uses 2 ceil(log2 n). for(k=3;k<=n;k++) A[k]=0; for(k=2;k<=TwoLog_n;k++) for(j=k+1;j<=n;j++) A[j]=A[j] || (j%k); for(j=3;j<=n;j++) if(!A[j]) printf("%d ",j); What set is printed? A. {m:m≤n and m=i! for some integer i} B. {m:m≤n and m=i² for some integer i} C. {m:m≤n and m is prime} D. ∅
Your answer
Answer & solution
Answer: D (no official key was published)
1. Logical OR leaves A[j]=0 only if every tested remainder j%k is zero. A nonzero remainder permanently sets the entry to 1. This is divisibility by every tested k, not primality testing. 2. Let L=TwoLog_n. For 3≤j≤L+1, the iteration k=j−1 is performed and leaves remainder 1, so none of those j prints. 3. For j>L+1, all k=2,...,L are tested. A printed j would therefore have to be a multiple of M=lcm(1,...,L). The useful bound M≥2L−1 follows because each binomial coefficient C(L−1,k) divides M/L, so summing the L coefficients gives 2L−1≤M. 4. With r=floor(log2 n) and L=2r, for n≥4 we have r≥2, hence M≥22r−1≥2r+1>n. No positive multiple can lie in the printing range. For n=3, k=2 marks 3 directly. 5. Nothing prints, D. The ceiling variant has at least the same tests, so also cannot print anything.
Solution: A[j] becomes true as soon as one tested k does not divide j; this is not a sieve that marks multiples. Let L be the outer-loop limit. If 3≤j≤L+1, the tested k=j−1 leaves remainder one, so j is not printed. For j>L+1, printing requires j to be divisible by every integer from 2 through L, hence by lcm(1,…,L). Let r=floor(log2 n), L=2r. For n≥4, the standard bound lcm(1,…,L)≥2L−1=22r−1≥2r+1>n rules this out. The n=3 case is directly marked by k=2. Thus nothing is printed, D. The LCM bound can also be established from the fact that every binomial coefficient in row L−1 divides lcm(1,…,L)/L, whose row sum is 2L−1.
Consider this C-style program (print emits its integer argument followed by a space): int x; void Q(int z) { z+=x; print(z); } void P(int *y) { int x=*y+2; Q(x); *y=x-1; print(x); } main(void) { x=5; P(&x); print(x); } What output is produced? A. 12 7 6 B. 22 12 11 C. 14 6 6 D. 7 6 6
Your answer
Answer & solution
Answer: A (no official key was published)
1. main sets the global x to 5 and passes its address, so y inside P points to that global object. 2. P declares a different, local x and initializes it to *y+2=5+2=7. Calling Q(x) copies 7 into Q's parameter z. 3. Q has no local x, so its x denotes the global, still 5. z becomes 7+5=12 and Q prints 12; this does not alter either x. 4. Back in P, *y=x−1 uses local x=7 on the right and writes 6 to the global through y. P prints its unchanged local 7. 5. main finally prints global x=6, producing 12 7 6, A. Passing the pointer allows the global update despite P's name shadowing.
Solution: main sets global x=5 and passes its address to P. P's local x becomes *y+2=7 and shadows the global only inside P. Q receives z=7; its unqualified x is the global 5, so z becomes 12 and Q prints 12. Returning to P, *y=x−1 writes 6 to the global, but P's local remains 7 and is printed. Finally main prints the global 6. The output is 12 7 6, A.
Select the correct statement about C. (A) At most one activation record lies between the current record and main’s record. (B) The number of activation records between the current record and main’s record depends on the actual sequence of function calls. (C) Visibility of global variables depends on the actual sequence of function calls. (D) Before a recursive call, the recursive function’s activation record must be saved on another stack.
Your answer
Answer & solution
Answer: B (no official key was published)
Step 1: Trace a concrete call chain.
Step 2: If main calls f and f calls g, the active stack contains main,f,g. If g recursively calls itself, another g activation is needed while the earlier one remains active. Thus the number of intervening records changes with actual calls. Lexical visibility is determined by declarations and scopes, not by this stack depth.
Conclusion: The runtime activation chain follows the actual sequence of function calls. Its depth between the current function and main therefore depends on that sequence, B. C uses lexical rather than dynamic scope for global names, and recursive calls can use successive records on the same runtime stack.
C declares char a[100][100]. Memory is byte-addressable, and the array starts at address 0. What is the address of a[40][50]? (A) 4040; (B) 4050; (C) 5040; (D) 5050.
Your answer
Answer & solution
Answer: B (no official key was published)
Step 1: Compute the linear index before the byte address.
Step 2: There are 40 complete rows before row40, each contributing 100 characters, and 50 earlier characters within that row. Therefore the zero-based linear index is 4000+50=4050. Since sizeof(char)=1, no further scale factor is needed. The5040 alternative reverses the row and column roles.
Conclusion: C lays out rows contiguously in row-major order. Each char occupies one byte, and each row has 100 elements. The offset of a[40][50] is 40×100+50=4050 bytes, giving address 4050 from the stipulated zero base, B.
Fill the three blanks in this recursive C template for Towers of Hanoi: void move(int n, char A, char B, char C) { if (____) { move(____); printf("Move disk %d from pole %c to pole %c\n", n, A, C); move(____); } } The task is to supply the condition and the arguments of both recursive calls.
Shared context
Complete all three blanks of a recursive C function move(n,A,B,C), whose printed central action moves disk n from pole A to pole C. B is the spare pole.
Answer & solution
Answer: Blanks: n > 0; n−1, A, C, B; n−1, B, A, C (no official key was published)
1. Infer the parameter roles from the printed central action. move(n,A,B,C) prints a move of disk n from A to C, so A is the source, C the destination, and B the spare pole. A recursive call must preserve this source/spare/destination order even when the pole names are permuted.
2. Fill the stopping condition. For zero disks there is nothing to move. Therefore execute the body only when n > 0. Using n > 1 would incorrectly skip the required single-disk move.
3. Clear the largest disk. Before disk n can move from A to C, the n−1 disks above it must move from A to B with C available as spare. In the function’s argument order this is move(n−1,A,C,B).
4. Move the largest disk, then restore the smaller tower above it. The printed action moves disk n from A to C. Next transfer the n−1 disks from B to C using A as spare, which is move(n−1,B,A,C).
5. The completed valid C function is:
void move(int n, char A, char B, char C)
{
if (n > 0) {
move(n - 1, A, C, B);
printf("Move disk %d from pole %c to pole %c\n", n, A, C);
move(n - 1, B, A, C);
}
}
Use the standard stdio declaration for printf in a complete program. The three blanks, in order, are n > 0; n−1,A,C,B; and n−1,B,A,C.
6. Check n=2 explicitly. The execution moves disk 1 A→B, disk 2 A→C, and disk 1 B→C. Each move is legal and the final tower is on C. For general n, assuming both smaller recursive transfers are legal establishes correctness by induction. The move count satisfies T(0)=0 and T(n)=2T(n−1)+1, hence T(n)=2n−1. Simulation verifies legality and final placement for n=1,…,8.
Three C functions return int pointers. P1 returns &x for automatic local int x=10. P2 declares uninitialized int *px, stores *px=10, then returns px. P3 allocates sizeof(int) with malloc, stores 10 through the pointer, and returns it. Which have pointer problems: only P3; P1/P3; P1/P2; all three? Distinguish the intended successful-allocation model from failure handling.
Your answer
Answer & solution
Answer: C under successful allocation for P3 (no official key was published)
Step 1: P1 returns the address of an automatic local int. Its lifetime ends when the function returns, so the returned pointer cannot be used to access that former object.
Step 2: P2 declares an uninitialized pointer and immediately writes through it. No valid target object has been established, causing undefined behavior.
Step 3: P3 allocates sizeof(int), writes 10 into the allocated object, and returns its pointer. Successfully allocated storage remains alive until freed, even after the function returns. Thus the intended contrast is P1 and P2, C.
Practical qualification: P3 must check malloc’s result before dereferencing it and the caller must eventually free it. If allocation fails, the unchecked P3 is also erroneous; appropriate declarations/headers are assumed.
abc(s) returns at the null terminator; otherwise it calls abc(s+1) twice and then prints s[0]. main calls abc("123").
Answer & solution
Answer: 3323321 (no official key was published)
Step through it (33 steps)
Let F(s) be the string printed by a call. F(empty)=empty and F(cs)=F(s)F(s)c. Therefore F("3")="3", F("23")="3"+"3"+"2"="332", and F("123")="332"+"332"+"1"="3323321". The recursive calls finish before the current character is printed, so the initial character appears last. No spaces or newline are printed.
The preceding abc routine is called on a null-terminated string of n characters, excluding the terminator.
Answer & solution
Answer: 2^n − 1 characters (no official key was published)
For n=0 the function immediately returns and prints zero characters. For n>0 it makes two calls on length n−1 and prints one character itself. Thus C(0)=0 and C(n)=2C(n−1)+1. Expanding gives C(n)=1+2+4+…+2n−1=2n−1. Equivalently, induction substitutes C(n−1)=2n−1−1 to get 2n−1. The null-terminator calls contribute no output. For n=3 this predicts seven characters, agreeing with 3323321.
Given struct node with int i and float j, followed by struct node *s[10], what is s: array of structure pointers, two-field structure of arrays, three-field structure, or array of structures?
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: Read outward from s. The immediately attached [10] makes s an array of ten elements.
Step 2: The preceding * says each element is a pointer, and the base type struct node says what it points to. Thus s is an array of ten pointers to nodes, A.
The node’s two fields describe each pointed-to object, not extra fields inside s. Writing struct node s[10] without * would instead produce the array of structures in D.
Answer: D: X3,Y1,Z2 (no official key was published)
Step 1: In X, assigning NULL over the sole saved address of a successful allocation loses the ability to free/access that block, creating lost memory or a leak:3.
Step 2: In Y, free ends the allocated object’s lifetime; the later dereference uses a dangling pointer:1. In Z, an uninitialized pointer has not been made to point at valid writable storage, so dereferencing it is an uninitialized-pointer error:2.
The mapping X3,Y1,Z2 is D. Successful allocation, no second saved reference, and initially valid n are the conventional premises for the first two examples.
A structure contains short s[5] and a union holding either float y or long z. short,float,long occupy 2,4,8 bytes. Ignoring alignment, choose size 22,14,18,10 bytes.
Your answer
Answer & solution
Answer: C (no official key was published)
Step 1: The array has five separate short objects, requiring 5·2=10 bytes.
Step 2: Union members share storage, so the union needs the maximum of 4 and 8 bytes, namely 8, rather than their sum. The enclosing structure stores its array and union separately.
Total size ignoring padding is 10+8=18 bytes, C. Adding both union members would incorrectly give 22; actual ABI alignment could add padding, explicitly excluded here.
Function incr(i) has static int count=0, executes count=count+i and returns count. main loops i=0 through 4 inclusive, assigning j=incr(i). Find final j among 10,4,6,7.
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: A static local is initialized once and retains its value between calls. The successive arguments are 0,1,2,3,4.
Step 2: The retained count becomes 0,1,3,6,10. Each returned value is assigned to j, so the final assignment stores 10.
Thus A. Reinitializing count on every call would incorrectly yield 4; stopping the loop before i=4 would yield 6, but the printed condition is inclusive.
Pseudo-Pascal: global x; Q(z) does z:=z+x; writeln(z). P(y) declares local x, does x:=y+2; Q(x); writeln(x). Main does x:=5; P(x); Q(x); writeln(x). Q and P are siblings declared in main. Find output under call-by-value and static scoping.
Answer & solution
Answer: 12
7
10
5 (no official key was published)
Main sets global x=5. P receives a separate value parameter y=5 and sets its local x=y+2=7. P calls Q(x), so Q receives a separate z=7. Static scoping resolves Q’s free x through its lexical declaration environment, main, not through the caller P: that x is the global 5. Therefore Q sets its own z=7+5=12 and prints 12. Because z was passed by value, P’s local x remains 7, so P next prints 7. Returning to main leaves global x=5. Main’s Q(x) receives z=5 and uses global x=5, so it prints 10; this changes only z. Finally main prints global x=5. The four outputs, one per writeln, are 12,7,10,5. Do not let P’s local x affect a statically scoped sibling procedure.
Pseudo-Pascal: global x; Q(z) does z:=z+x; writeln(z). P(y) declares local x, does x:=y+2; Q(x); writeln(x). Main does x:=5; P(x); Q(x); writeln(x). Q and P are siblings declared in main. Find output under call-by-reference and dynamic scoping.
Answer & solution
Answer: 14
14
10
10 (no official key was published)
Main’s x starts at 5. In P(x), y aliases main’s x, but P also owns a distinct local x. It reads y=5 and assigns local x=7. Q(x) is then called with a reference to that local x, so z aliases P.x. Under dynamic scoping, Q’s free x resolves to the nearest active caller with an x, also P.x. The assignment z:=z+x therefore reads 7+7 and writes 14 into P.x. Q prints 14, and P’s next writeln(x) prints the same 14. Main’s global x is still 5 because neither assignment changed y or main.x. After P returns, main calls Q(x); now both reference parameter z and dynamically resolved x refer to main.x. Their old values are 5, so the assignment writes 10 into main.x. Q prints 10 and main’s final writeln(x) also prints 10. Aliasing and name resolution are separate steps: first identify each referenced storage cell, then evaluate the addition using its pre-assignment value.
Trial(a,b,c) returns b if a≥b and c<b; otherwise calls Trial(a,c,b) if a≥b, or Trial(b,a,c). Does it find maximum,minimum,median,or none?
Select all that apply
Answer & solution
Answer: C on distinct values; not total for arbitrary integers (no official key was published)
For distinct values, a return requires c<b≤a, so b is the median. If a<b, swapping the first two puts the larger first. If a≥b but c≥b, swapping b and c either puts the middle value second or is followed by a first-pair swap; direct enumeration of the six strict orderings confirms termination at the median. Ties expose a defect: Trial(2,1,1) repeatedly calls itself because c<b is false while swapping equal arguments changes nothing. Trial(1,1,1) likewise never returns. Thus C describes the intended distinct-input algorithm, but no unconditional median function is established by the stated unrestricted int signature.
For this program, determine printed a under call by value: procedure P(x,y,z); begin y := y+1; z := x+x end; begin a := 2; b := 3; P(a+b,a,a); print(a) end. The initialization a:=2 is supplied by GFG; GateForum omits it.
Answer & solution
Answer: 2 (no official key was published)
At entry the actual expression a+b is evaluated to 5. Call by value creates three independent local cells x=5, y=2 and z=2. The first assignment changes only local y from 2 to 3. The second computes local z=x+x=10. Neither assignment writes caller a; the local cells disappear when P returns. Hence caller a remains 2 and print(a) outputs 2. The two occurrences of actual a do not create aliases in call by value.
Determine printed a under call by reference for: procedure P(x,y,z); begin y := y+1; z := x+x end; begin a := 2; b := 3; P(a+b,a,a); print(a) end. Use GFG’s visible a:=2 initialization, absent in GateForum, and discuss passing the expression a+b by reference.
Answer & solution
Answer: 10 under expression-temporary convention; strict variable-reference semantics reject the call. (no official key was published)
There is a language-semantic qualification: an ordinary assignable reference parameter cannot bind to the non-variable expression a+b. In a strict Pascal-style var-parameter language this call is invalid, so no output is defined. The customary exercise convention evaluates a+b once into an anonymous temporary t=5 and binds x to t, while both y and z refer directly to caller a. Then y:=y+1 changes a from 2 to 3. Next z:=x+x reads t twice, obtains 10, and writes a=10. Thus the intended trace under that convention prints 10. It does not print 12: reevaluating a+b after a changes would be call-by-name behavior, not a reference to the original temporary. The convention and the secondary initialization must both be stated rather than silently assumed.
Determine printed a under call by copy-restore for: procedure P(x,y,z); begin y := y+1; z := x+x end; begin a := 2; b := 3; P(a+b,a,a); print(a) end. GFG supplies a:=2, which is missing in GateForum. No copy-back order is specified.
Answer & solution
Answer: 10 if y restores before z; 3 if z restores before y; no unique output without a convention. (no official key was published)
Copy-in gives independent local values x=5, y=2, z=2. The body ends with x=5, y=3, z=10. Both y and z have the same copy-back destination, caller a, so restoration order matters. Restoring y then z sets a first to 3 and then to 10, printing 10. Restoring z then y sets a first to 10 and finally to 3, printing 3. Thus the given program has no uniquely determined copy-restore result unless the language specifies the order. A left-to-right formal-parameter restoration convention yields 10. As in reference passing, the non-variable actual a+b requires an expression temporary or a rule permitting input-only expressions; strict copy-in/copy-out parameters requiring assignable actuals reject the call. Under the temporary convention restoring unchanged x does not affect a. This is aliasing at copy-back, not aliasing between the local parameter cells.
Consider this pseudo-Pascal program, where z is global: program what; var z:integer; procedure recur(x); begin if x<=40 then begin x:=x+z; recur(x); z:=x+10 end end; begin z:=10; recur(z); writeln(z) end. If x is passed by value, what is printed?
Answer & solution
Answer: 30. (no official key was published)
Step through it (13 steps)
Pass by value gives every call its own local x, but all calls still share the same global z. It is important not to copy z into each activation or to overwrite a caller's x with its child's final x.
On descent, no assignment z:=x+10 has executed yet: it comes after the recursive call. Therefore z stays 10 while the successive calls enter with x=10,20,30,40,50. The calls entering with 10,20,30,40 first update their local x to 20,30,40,50 respectively. The final call enters with x=50; because 50≤40 is false, it immediately returns.
The outer call is last to write the shared global, so writeln(z) prints 30. The temporary value 60 produced by the deepest active body is not the final answer. Also, x=40 does execute its body, because both visual sources show ≤40 rather than <40. The individual marks for this nested leaf are not printed; they are left unknown rather than assigning an invented share of the original group's marks.
Consider this pseudo-Pascal program, where z is global: program what; var z:integer; procedure recur(x); begin if x<=40 then begin x:=x+z; recur(x); z:=x+10 end end; begin z:=10; recur(z); writeln(z) end. If x is passed by value, how many times is recur called, including the call from the main program?
Answer & solution
Answer: 5 total calls, of which 4 are recursive calls. (no official key was published)
Step through it (13 steps)
At every recursive descent, the global z is still 10, since z is assigned only after recur(x) returns. Each active call therefore adds 10 to its own copy of x and invokes the next call. The entry arguments are
The first four entries satisfy x≤40 and execute the recursive-call statement. The last entry, with x=50, fails the test and returns without another call. It is nevertheless an invocation and must be included when counting how many times recur is called. Thus there are five calls in total, four of them made recursively by the procedure itself.
A count of four confuses the number of executed recursive-call statements, or the number of nonbase activations, with the total requested calls. A count based on doubling x would instead be using reference semantics, in which x aliases z; that is not this subpart. The literal ≤ is also essential: a call with argument 40 recurses once more. Original10(a)(ii) is a separate normalized leaf, but neither source prints its own mark allocation, so its marks remain null.
Consider this pseudo-Pascal program, where z is global: program what; var z:integer; procedure recur(x); begin if x<=40 then begin x:=x+z; recur(x); z:=x+10 end end; begin z:=10; recur(z); writeln(z) end. If x is passed by reference, what is printed?
Answer & solution
Answer: 110. (no official key was published)
Step through it (11 steps)
The main program calls recur(z), so its reference parameter x is another name for the global variable z. Passing that reference onward as recur(x) keeps the same alias in every activation. There are not separate saved integer values of x in the suspended calls.
Initially x=z=10. The first body executes x:=x+z, doubling the shared variable to 20. The next call doubles it to 40. Because the guard is x≤40, the call seeing 40 also executes the body and doubles it to 80. The next call sees 80 and returns immediately. Thus four activations exist, three with a pending final assignment.
On unwinding, every z:=x+10 reads the current shared value, because x aliases z. The three pending assignments make the values 80→90→100→110. The program consequently prints 110.
It would be incorrect to use the descent values 10,20,40 as saved local copies during unwinding: that is pass-by-value behavior. It would also be incorrect to stop at 80, since the three assignments following recursive calls still have to execute. The example shows why mutation of a reference argument can interact unexpectedly with a global variable naming the same storage location.
For N>1, the following Pascal-like program searches an array a[1..N]: initialize i=1,j=N; repeatedly set k=floor((i+j)/2), then if a[k]<x set i=k, otherwise set j=k; stop when a[k]=x or i>=j. Finally print success if a[k]=x and failure otherwise. Determine when it fails. For the intended binary-search interpretation assume a is sorted in nondecreasing order. GFG prints the success message correctly; GateForum instead prints failure in both final branches.
Answer & solution
Answer: It loops when x>a[1] and x is not in positions 1..N−1; in particular a unique match at the last element is missed (no official key was published)
The defect is that the lower update keeps the already examined element: i=k instead of i=k+1. When j=i+1, integer division gives k=i. If a[i]<x, setting i=k changes nothing; j also stays unchanged, a[k] is not x, and i<j remains true. The loop repeats forever.
In fact the final array position N is never examined: while i<j, floor((i+j)/2)<j<=N, so k<=N−1. On a nondecreasing array, the exact classification is: every x occurring among a[1],...,a[N−1] is eventually found; every x<a[1] terminates with failure; every x>a[1] absent from a[1..N−1] loops forever. The latter includes absent values between array entries, values above the maximum, and x=a[N] when that value occurs only at the last position. Duplicates matter: x=a[N] is found if the same value occurs earlier.
For example a=[1,3], x=3 gives (i,j,k)=(1,2,1) forever. With x=0, the first iteration instead sets j=1 and terminates correctly. For a=[1,3,5], x=3 is examined immediately and succeeds. These examples distinguish the actual bug from the inaccurate claim that all unsuccessful searches fail.
A robust repair uses while i<=j, tests equality first, then sets i=k+1 when a[k]<x and j=k−1 otherwise, reporting failure after the interval becomes empty. This also permits examining N.
Global b is set to 3 and test1(b) is called. Procedure test1(a) sets a=5, prints “point 1:” followed by a,b, calls test2, then prints “point 2:” followed by a,b. Procedure test2 sets the global b=10. After test1 returns, the main program prints “point 3:” followed by b. Assume the displayed lexical scope and determine the output with a passed by reference.
Answer & solution
Answer: point 1: 5 5; point 2: 10 10; point 3: 10. (no official key was published)
A reference parameter is another name for the caller's variable, not a private copy of its value. Here the actual parameter is the global b, so a and b designate the same storage throughout test1. Initially that cell contains 3. Executing a:=5 updates the cell itself, which means both a and b now read as 5. Consequently the first output is point 1: 5 5.
Next test2 executes b:=10. It refers to the global b by the displayed lexical scope; this is the same cell already aliased by a. Therefore both reads at the second output produce 10, giving point 2: 10 10. Returning from test1 requires no copy-back for a reference parameter. The global value remains 10, and the final output is point 3: 10.
The important reasoning is storage identity: a:=5 changes b immediately, and test2's assignment to b changes what a observes immediately. The procedure nesting does not create a second b or hide the global declaration. Spaces and line breaks may depend on Pascal's output formatting; the value sequences, in order, are (5,5), (10,10), and (10).
Global b is set to 3 and test1(b) is called. Procedure test1(a) sets a=5, prints “point 1:” followed by a,b, calls test2, then prints “point 2:” followed by a,b. Procedure test2 sets the global b=10. After test1 returns, the main program prints “point 3:” followed by b. Assume the displayed lexical scope and determine the output with a passed by value-result (copy-in/copy-out).
Answer & solution
Answer: point 1: 5 3; point 2: 5 10; point 3: 5. (no official key was published)
Value-result creates a separate local parameter cell. At entry to test1, the current actual value b=3 is copied into a. The assignment a:=5 changes only that private cell; the global b remains 3. Thus the first output is point 1: 5 3.
The call to test2 then assigns 10 to the global b. It does not refer to the private parameter a of its caller, so a stays 5. The second output is consequently point 2: 5 10. This is the observable difference from call-by-reference: a is not an alias for b during the call.
At normal return from test1, the result phase copies the final local a back to the original actual parameter location b. That overwrites test2's value 10 with 5. The main program therefore prints point 3: 5. The chronological storage states are (a,b)=(3,3) at entry, (5,3) after assigning a, (5,10) after test2, and b=5 after copy-out. No conflict among multiple value-result actuals arises because the procedure has just one parameter. If it were ordinary call-by-value instead, there would be no final copy-back and point 3 would show 10; the word “result” is essential.
Complete blanks A, B, C in this Pascal-like function, for integer −8≤N≤7: if N<0 then N:=A; BINARY:=0; EXPONENT:=1; while N<>0 do begin REM:=N mod 2; BINARY:=BINARY+B*EXPONENT; EXPONENT:=EXPONENT*10; N:=C end; TWOSCOMP:=BINARY. REM, EXPONENT and BINARY are integer variables. The returned decimal integer has the binary digits as its decimal digits. GFG declares REM; GateForum declares RAM but uses REM.
Answer & solution
Answer: A=N+16; B=REM; C=N div 2. (no official key was published)
Four bits represent signed values from −8 to 7. A negative N has the same four-bit pattern as the unsigned residue N+24=N+16. Thus the first blank is N+16: −8 maps to 8 (1000), and −1 maps to 15 (1111). Nonnegative inputs need no conversion before digit extraction.
For a nonnegative integer, N mod 2 is its least significant binary digit. The current EXPONENT is 1,10,100,1000, so adding REM*EXPONENT puts that bit in the corresponding decimal digit position of the returned integer. Hence B is REM. Integer division N div 2 discards the extracted bit; hence C is N div 2, not real division. Each iteration reduces the nonzero quotient and the loop terminates.
For N=−3, convert to 13. The remainders are 1,0,1,1, the accumulating decimal result is 1,1,101,1101, and the quotients are 6,3,1,0. Thus the result 1101 denotes the correct four-bit pattern. N=0 skips the loop and returns 0; positive outputs omit leading zero digits because they are stored as integers. Displaying exactly four bits requires zero-padding separately. Outside the guarded range the printed function does not assign its return value.
What function of integer x,n is computed by this program? function what(x,n): value := 1; if n > 0 then begin if n mod 2 = 1 then value := value*x; value := value*what(x*x,n div 2); end; return value;
Answer & solution
Answer: x^n for n≥0 under exact arithmetic; 1 for n<0. (no official key was published)
1. For n≤0 the conditional is skipped and the return value is one.
2. Write positive n=2k+r, where r∈{0,1}. The function returns xr times what(x²,k).
3. Induct on n. The recursive argument k<n, and the induction hypothesis gives (x²)k. Hence the result is x2k+r=xn.
4. The recursion depth and multiplication count are O(log n). Fixed-width integer overflow can change the numerical result; no word size is specified.
fib(n)=1 for n=0 or 1; otherwise fib(n)=fib(n−1)+fib(n−2). The available stack is 64 bytes. Each activation stores only a 2-byte return address and a 2-byte integer parameter. Estimate the largest nonnegative n without overflow. GateForum prints parameter “1” in the header but uses n in the body; GFG uses n.
Answer & solution
Answer: n=16 under the stipulated 4-byte-per-activation model, counting the initial fib call. (no official key was published)
Each active invocation occupies 2+2=4 bytes, so the stack can hold 64/4=16 simultaneously active invocations. The relevant quantity is peak recursion depth, not the exponentially growing total number of calls: completed calls return and free their space before their siblings finish.
Let D(n) be the largest number of simultaneously active fib frames, including the current frame. D(0)=D(1)=1, and for n≥2, D(n)=1+max(D(n−1),D(n−2)). It follows that D(n)=n for n≥1. For example fib(3)→fib(2)→fib(1) contains three active frames; the longest chain from fib(n) descends through n−1,n−2,…,1. The alternative final call at zero has no extra level, because fib(1) is a base case and does not call fib(0).
Therefore n=16 uses exactly 64 bytes, while n=17 needs 68 bytes. Both base cases need just four bytes. This estimate assumes the full 64 bytes are available to fib, its initial activation is stack-resident, and intermediate results, frame links, saved registers and runtime bookkeeping incur no further stack charge, exactly as stipulated. A real implementation may need more storage. Excluding the initial activation would shift the numerical bound to 17, but that is a different accounting convention, not the model used here.
Replace Pascal if x>5 then y:=true else y:=false with one assignment.
Answer & solution
Answer: y := (x > 5); (no official key was published)
The comparison x>5 evaluates to a Boolean. In the true case, the original statement assigns true to y; in the false case, it assigns false. Assigning the comparison result therefore gives exactly the same value in both cases. At x=5, the result is false, so using ≥ instead would be incorrect. This simplification assumes y has Boolean type and the comparison has the ordinary Pascal semantics shown in the source. No branch or numeric Boolean encoding is needed.
Rewrite Pascal repeat S until B using a while construct with equivalent behavior.
Answer & solution
Answer: begin S; while not B do S end (no official key was published)
A repeat loop executes S before checking B, so S runs at least once. Execute S once explicitly, then test not B in the while guard. Whenever B remains false, execute S again; stop immediately after an iteration makes B true. Merely writing while not B do S would incorrectly permit zero executions when B starts true. This transformation preserves the sequence of evaluations of B after executions of S, including ordinary side effects in the condition. If S is a multi-statement sequence, it must be grouped as a Pascal compound statement.