C# Programming - Control Instructions - Discussion

Discussion :: Control Instructions - General Questions (Q.No.5)

5. 

Which of the following is the correct way to rewrite the following C#.NET code snippet given below?

int i = 0; 
do
{
    Console.WriteLine(i);
    i+ = 1; 
} while (i <= 10);

[A].
int i = 0; 
do
{
    Console.WriteLine(i);
} until (i <= 10);
[B].
int i;
for (i = 0; i <= 10 ; i++)
    Console.WriteLine(i);
[C].
int i = 0; 
while (i <= 11)
{
    Console.WriteLine(i);
    i += 1; 
}
[D].
int i = 0;
do while ( i <= 10)
{
    Console.WriteLine(i); 
    i += 1;
}
[E].
int i = 0;
do until (i <= 10)
{
    Console.WriteLine(i);
    i+=1; 
}

Answer: Option B

Explanation:

No answer description available for this question.

Nikhil said: (Oct 11, 2014)  
For loop has no opening and closing braces here. Then its syntax is wrong here.

Vinay said: (Jun 24, 2015)  
There is no need of braces for a single line of code.

Vikram said: (Jul 8, 2015)  
Without brackets single line of code will execute. Please tell me.

Inathi Gqola said: (Jul 30, 2015)  
Yes, the syntax is totally correct. The practice is wrong though. So unreadable.

Pankaj Chauhan said: (Sep 10, 2015)  
Option C should be correct answer. Because do while will print 11. Hence C is the correct answer.

Pankaj Chauhan said: (Sep 10, 2015)  
Option C is correct answer. In above scenario do while loop will print 11. So option C should be the correct answer.

Ragni said: (Nov 9, 2015)  
But what is wrong in the original code? or option (A)?

Sunshine said: (Dec 4, 2016)  
@Pankaj Chauhan, Why do you think that do while will print 11? It won't because 11 is not less or equal to 10. It will evaluate false and exit the loop, and 11 won't be printed.

Madusha Rathnayake said: (Sep 23, 2019)  
Option B is correct obviously.

But in the syntax instead of being i+ = 1; it should be i += 1; . On the other hand , it will not print 11 because the increment code is given after the output code. If the code inside "{ }" changed their order then 11 would print.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.