Consider the following program in C:
#include <stdio.h>
void func(int i, int j) {
if(i < j) {
int i = 0;
while (i < 10) {
j += 2;
i++;
}
}
printf("%d", i);
}
int main() {
int i = 9, j = 10;
func(i, j);
return 0;
}The output of the program is . (answer in integer)
Note: Assume that the program compiles and runs successfully.
View worked solution
Answer: 09 :09
To find the output of the program, let's trace the execution step-by-step:
- The
main()function callsfunc(9, 10), passingi = 9andj = 10. - Inside
func(int i, int j), the conditionif (i < j)(i.e.,9 < 10) is true. - Inside the
ifblock, a new local variableint i = 0;is declared. This variable shadows the parameteriwithin the scope of theifblock. - The
while (i < 10)loop increments this inneriup to10. - Once the
ifblock terminates, the innerigoes out of scope and is destroyed. - The
printf("%d", i);statement is outside theifblock, so it refers to the parameteri, which remains unchanged with its original value of9.
Thus, the program prints 9.
Free practice · Your answers on this page are not saved.
