ExamVeda
Login
Home
Basic Syntax and Data Types in C Sharp
?

What will be the output of the following C# code?
class Program
{
    static void Main(string[] args)
    {
        int i;
        for ( i = 0; i < 5; i++)
        {
 
        }
        Console. WriteLine(i);
        Console. ReadLine();
    }
}

Answer & Solution
Correct Answer: Option C
The correct answer is C: 5
Here's why:
Let's break down the code step by step:
int i; declares an integer variable named 'i'.
for (i = 0; i < 5; i++) is a for loop. Let's see how it works:
i = 0; This is the initialization part. 'i' starts at 0.
i < 5; This is the condition. The loop continues as long as 'i' is less than 5.
i++; This is the increment. After each loop iteration, 'i' increases by 1.
The loop runs as follows:
i = 0 (0 < 5 is true)
i = 1 (1 < 5 is true)
i = 2 (2 < 5 is true)
i = 3 (3 < 5 is true)
i = 4 (4 < 5 is true)
i = 5 (5 < 5 is false) The loop stops here.
Console.WriteLine(i); This line prints the final value of 'i', which is 5.
Console.ReadLine(); This line just waits for you to press Enter before the program closes (it keeps the console window open so you can see the output).
Examveda
Question posted by Examveda
Community

Join the Discussion

1 Comment
Mohamed Gamal
Mohamed Gamal 2 years ago
why c