What will be the output of the following C# code? [code] static void Main(string[] args) { int i; i = 0; while (i++ <

Minh Phượng

New member
What will be the output of the following C# code?
Code:
 static void Main(string[] args)
 {
     int i;
     i = 0;
     while (i++ < 5)
     {
         Console.WriteLine(i);
     }
     Console.WriteLine("\n");
     i = 0;
     while ( ++i < 5)
    {
        Console.WriteLine(i);
    }
    Console.ReadLine();
}
A.
1 2 3 4
1 2 3 4 5
B.
1 2 3
1 2 3 4
C.
1 2 3 4 5
1 2 3 4
D.
1 2 3 4 5
1 2 3 4 5
 
Answer: c
Explanation: For while(i++ < 5) current value of 'i' is checked first and hence prints incremented value afterwards. So, i =1, 2, 3, 4, 5. But, for while(++i < 5) current value is incremented first and then checks that value with given condition and hence then prints that value. So, i = 1, 2, 3, 4.
Output:
Code:
        1 2 3 4 5
        1 2 3 4
 

Tìm kiếm

Back
Top