All Exams Test series for 1 year @ ₹349 only
Question

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.

C Program Code Analysis

The provided C program consists of a $main$ function and a function named $func$.

The $main$ function initializes two integer variables: $i$ to 9 and $j$ to 10. It then calls the $func$ function, passing the current values of $i$ and $j$ as arguments.

Function func Scope and Execution

The $func$ function receives $i=9$ and $j=10$ as its parameters.

The condition $if (i < j)$ evaluates to true because $9 < 10$.

Inside the $if$ block, a new local variable named $i$ is declared using $int i = 0;$. This declaration creates a variable local to the $if$ block's scope, initializing it to 0. This local $i$ effectively hides or "shadows" the parameter $i$ (which holds the value 9).

The $while (i < 10)$ loop begins. This loop operates on the newly declared local variable $i$.

  • Inside the loop, $j += 2;$ increments the function's parameter $j$.
  • Simultaneously, $i++;$ increments the local variable $i$.

The loop executes as long as the local $i$ is less than 10. After 10 iterations (when local $i$ progresses from 0 to 9), the loop condition becomes false. At this point, the local variable $i$ holds the value 10.

Following the loop, the statement $printf("%d", i);$ is executed. According to C's scope rules, this statement refers to the variable $i$ that is accessible in its current scope. This is the local variable $i$, whose value is 10.

Final Output Value

The execution analysis indicates that the printf statement within the function will output the value of the local variable $i$ after the loop finishes.

The correct value is 9.

Was this answer helpful?

Important Questions from Scope of a Variable

  1. Which of the following is not true about Global Variables:

Need Expert Advice?

Start Your Preparation with Prepp Mobile App

Download the app from Google Play & App Store
Download the app from Google Play & App Store
Prepp Mobile App