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();
}
}
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: 5Here'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)
Related Questions on Basic Syntax and Data Types in C Sharp
What is the correct syntax to declare a variable in C#?
A. num = int;
B. var num;
C. num int;
D. int num;
What is the purpose of the 'var' keyword in C#?
A. Declares a constant
B. Converts a variable to string
C. Implicitly declares a variable
D. Defines a method

why c