What will be the output of the following C# code?
static void Main(string[] args)
{
int i ;
for (i = 0; i < 5; i++)
{
int j = 0;
j += i;
Console. WriteLine(j);
}
Console. WriteLine( i * j);
Console. ReadLine();
}
static void Main(string[] args)
{
int i ;
for (i = 0; i < 5; i++)
{
int j = 0;
j += i;
Console. WriteLine(j);
}
Console. WriteLine( i * j);
Console. ReadLine();
}
A. 0, 1, 6, 18, 40
B. 0, 1, 5, 20, 30
C. Compile time error
D. 0, 1, 2, 3, 4, 5
Answer: Option C
Solution (By Examveda Team)
Understanding the Code:This C# code uses a for loop to repeat a block of code five times.
Inside the loop, a variable
j
is declared and initialized to 0 in each iteration.Then,
j
is updated by adding the current value of i
to it (j += i;
).The value of
j
is printed to the console in each iteration.After the loop finishes, the code tries to print
i * j
. However, this is tricky! The scope of j
is only inside the loop. Once the loop finishes, j
no longer exists.Therefore, you will get a compile-time error because
j
is not accessible outside the loop. Why other options are incorrect:
Options A, B, and D show possible outputs if the code were to run without error. Since
j
is out of scope, these outputs are impossible. The Correct Answer:
The correct answer is C: Compile time error because the variable
j
is not accessible outside the for
loop.
The name 'j' does not exist in the current context