Examveda

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();
    }
}

A. 0, 1, 2, 3, 4, 5

B. 0, 1, 2, 3, 4

C. 5

D. 4

Answer: Option C

Solution (By Examveda Team)

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).

Join The Discussion

Comments (1)

  1. Mohamed Gamal
    Mohamed Gamal:
    7 months ago

    why c

Related Questions on Basic Syntax and Data Types in C Sharp