Question Details

Consider the following program, what is the output printed ? void f(int i, int j)  { i = 0; while (i < 10) { j = j + 2; i++; } printf(i); } } int main() { int i = 9, int j = 10; f(i, j); return 0; }

Show Answer

Correct Answer :

10

Solution :

The correct answer is 10.

Let us analyze the program step-by-step to understand why the output is 10:

1. Function Call and Initialization:
In the main() function, the variables i and j are initialized as i = 9 and j = 10. The function f(i, j) is then called, passing these values by value to the local parameters i and j inside f.

2. Variable Reassignment inside f():
At the beginning of function f, the parameter i is immediately reassigned to 0:
i=0
Thus, the initial value of 9 passed from main() is overwritten.

3. The While Loop:
The loop condition checks:
i<10
In each iteration of the loop, the following actions occur:
- j is incremented by 2 (j = j + 2).
- i is incremented by 1 (i++).

4. Loop Termination and Printing:
The loop starts with i = 0 and increments i by 1 in each step. The iterations proceed as follows:
- After 1st iteration: i = 1
- After 2nd iteration: i = 2
- ...
- After 10th iteration: i = 10
When i reaches 10, the loop condition i < 10 (10 < 10) becomes false, and the loop terminates. After the loop, the program prints the value of i. Since the final value of i is 10, the output printed is 10.

Unlock Our Free Library

Access expert-curated educational resources and study materials—completely free.

Ask AI Tutor
5 left
Q1 View Question & Options
AI Tutor is solving this question...
Reading question context & options...