?
What will be the output of the following C# code?
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();
}
Answer & Solution
Correct Answer:
Option
C
Understanding the Code:
This C# code uses a for loop to repeat a block of code five times.
Inside the loop, a variable
Then,
The value of
After the loop finishes, the code tries to print
Therefore, you will get a compile-time error because
Why other options are incorrect:
Options A, B, and D show possible outputs if the code were to run without error. Since
The Correct Answer:
The correct answer is C: Compile time error because the variable
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.
Join the Discussion
Login to post a comment or share your explanation.
Login