- Get link
- X
- Other Apps
Consider the following C program:
#include
int gate (int n) {
int d, t, newnum, turn;
newnum = turn = 0; t=1;
while (n>=t) t *= 10;
t /=10;
while (t>0) {
d = n/t;
n = n%t;
t /= 10;
if (turn) newnum = 10*newnum + d;
turn = (turn + 1) % 2;
}
return newnum;
}
int main () {
printf ("%d", gate(14362));
return 0;
}
The value printed by the given C program is ______. (Answer in integer)
The correct answer is 46.
The C program's `gate` function isolates each digit of the input number from left to right. A `turn` variable alternates between 0 and 1. The `if (turn)` condition ensures that only digits from even positions (2nd, 4th, 6th, etc.) are used to build a new number. For the input 14362, the 2nd digit (4) and the 4th digit (6) are selected, forming the number 46, which is printed.
To determine the output, we need to trace the execution of the `gate(14362)` function step by step.
Code Analysis
The `gate` function essentially does the following:
- It determines the place value of the most significant digit of the input `n` and stores it in `t`. For `n = 14362`, `t` will become `10000`.
- It then iterates through the number digit by digit from left to right.
- A variable `turn` acts as a flag, toggling between 0 and 1.
- The line
if (turn)means a digit is only appended to `newnum` if `turn` is 1 (i.e., on the 2nd, 4th, 6th... iterations).
Step-by-Step Execution Trace
Let's trace the main `while (t > 0)` loop with the input `n = 14362`.
Initial values before the loop: `newnum = 0`, `turn = 0`, `t = 10000`.
| Iteration | `t` (start) | `d = n/t` | `n = n%t` | `turn` (before if) | `if(turn)` fires? | `newnum` (end) | `turn` (end) |
|---|---|---|---|---|---|---|---|
| 1 | 10000 | 1 | 4362 | 0 | No | 0 | 1 |
| 2 | 1000 | 4 | 362 | 1 | Yes | 10*0 + 4 = 4 | 0 |
| 3 | 100 | 3 | 62 | 0 | No | 4 | 1 |
| 4 | 10 | 6 | 2 | 1 | Yes | 10*4 + 6 = 46 | 0 |
| 5 | 1 | 2 | 0 | 0 | No | 46 | 1 |
The loop terminates as `t` becomes 0. The function returns the final value of `newnum`, which is 46.
The `main` function then prints this returned value.
- Kernighan, B. W., & Ritchie, D. M. (1988). The C Programming Language. Prentice Hall.
- Prata, S. (2014). C Primer Plus. Addison-Wesley Professional.
- Get link
- X
- Other Apps
Comments
Post a Comment
Ask you doubt here