Consider the following C program:
#include <stdio.h>
int gate (int n) {
int d, t, newnum, turn;
newnum = turn = 0; t=1;
while (n>=t) t *= 10;
t /=10;
while (t>0) {
d = n/t;
n = n%t;
t /= 10;
if (turn) newnum = 10*newnum + d;
turn = (turn + 1) % 2;
}
return newnum;
}
int main () {
printf ("%d", gate(14362));
return 0;
}The value printed by the given program is ________. (Answer in integer)
View worked solution
Answer: 46:46
Let's trace the execution of the function gate(14362) step-by-step:
Step 1: Determine the initial value of
The first while (n >= t) loop finds the smallest power of greater than . For , the loop terminates when .
After the loop, t /= 10; sets .
Step 2: Extract digits and construct newnum
The second while (t > 0) loop extracts the digits of from left to right (most significant to least significant) and alternates selecting them using the turn flag:
- Iteration 1:
- , , .
- Since
turn == 0,newnumremains . turnbecomes .
- Iteration 2:
- , , .
- Since
turn == 1,newnum = 10 * 0 + 4 = 4. turnbecomes .
- Iteration 3:
- , , .
- Since
turn == 0,newnumremains . turnbecomes .
- Iteration 4:
- , , .
- Since
turn == 1,newnum = 10 * 4 + 6 = 46. turnbecomes .
- Iteration 5:
- , , .
- Since
turn == 0,newnumremains . turnbecomes .
The loop terminates because . The function returns newnum, which is 46.
Free practice · Your answers on this page are not saved.
