C# Programming - Control Instructions - Discussion

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

1. 

What does the following C#.NET code snippet will print?

int i = 0, j = 0; 

label:
    i++;
    j+=i;
if (i < 10)
{
    Console.Write(i +" ");
    goto label; 
}

[A]. Prints 1 to 9
[B]. Prints 0 to 8
[C]. Prints 2 to 8
[D]. Prints 2 to 9
[E]. Compile error at label:.

Answer: Option A

Explanation:

No answer description available for this question.

Arun said: (Aug 31, 2011)  
How does console.writeline statement is executed?

Sibi said: (Feb 15, 2012)  
Here the output will be error.one main thing is the print statement itself is wrong.

Vimala said: (Aug 16, 2012)  
console.write will execute as it mean to produce output, when the code gets executed the i++ inside the label will be incremented ,that is why it's from 1 to 10

Kazeem said: (Jul 9, 2013)  
Whenever We are working with Labels, Label gets Executed Even if it is not called. so for the first time i value will be incremented to 1 and then control passes to if condition there it prints i value(1).

Then label is called from if body. Now again i value is incremented to 2. So it repeats until condition in if becomes false. So we get output As 1 to 9.

Raveendra Bj said: (Dec 26, 2013)  
The o/p is 123456789,

Why? because everytime i++ increment the i value.

And goto statement sends control.

There is nothing evil in this code.

Thanks!

Ashish said: (Sep 15, 2014)  
Code must be as:

int i = 0, j = 0;

label:
i++;
j += i;
if (i < 10)
{
Console.WriteLine(i + " ");

goto label;

}
Console.ReadLine();

Then output will be 1 to 9.

Rohan said: (Mar 19, 2015)  
Why did we use j here?

Ankush said: (Aug 28, 2015)  
Sir can you tell me how += operator works?

Suvarna said: (Mar 26, 2016)  
j+=i; means,

j=j+i;

Shaharukh said: (Oct 9, 2016)  
I think lable1 is considered as case and that's why it will give output.

Koti said: (Feb 16, 2017)  
J+=i?
J+i=i

Is it right or worng?

Please tell me.

Pavithra said: (Oct 13, 2017)  
J+=i says j=i+1
J+i=i

Both are same @Koti.

Sivaleela said: (Jan 6, 2019)  
It's not a while loop, it is just an if loop then how may it will repeat the loop. I think it will print only 1.

Output = 1

Ankita said: (Aug 8, 2019)  
It's a loop. If the condition gets true, it will go further until it gets false.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.