C# Programming - Control Instructions - Discussion

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


What will be the output of the C#.NET code snippet given below?

int val;
for (val = -5; val <= 5; val++)
    switch (val)
        case 0:
            Console.Write ("India"); 
    if (val > 0)
        Console.Write ("B"); 
    else if (val < 0)
        Console.Write ("X");

[A]. XXXXXIndia
[B]. IndiaBBBBB
[E]. Zero

Answer: Option C


No answer description available for this question.

Anusha said: (Dec 27, 2011)  
The correct answer is A but not C because when executing case 0 there is break so that it junps out of for loop and the other is not printed.

Sumit said: (Jun 3, 2012)  
Answer given by India bix is right as break statement make the instruction pointer jump out from the switch {} not from for loop.

Sajila said: (Dec 18, 2012)  
This answer is correct. Control first come to the for loop then val=-5 and satisfy condition then come to the switch but case is mismatch then come to the if and it also wrong then work the else part and each time val will be incremented until the else part become false. Then control satisfy the switch case and execute its statement then if condition check with new value of val and satisfy the condition. Then execute its statement. After these exit from the or loop. Now the output of this is XXXXXIndiaBBBBB.

Sneha Waghmare said: (Nov 26, 2015)  
The answer is correct given by IndiaBix.

Sunshine said: (Dec 4, 2016)  
The answer is indeed C. The break statement breaks out from the switch statement, not from the for loop.

Sai Charan said: (Jul 26, 2017)  
In the for-loop the value is initialized to -5.

(val <= 5) condition becomes false.
it doesn't satisfy the condition of the Switch case. So,
It Enters into if statement.It doesn't satisfy that condition.
as well.It jumps to else if statement. It satisfies the condition and "x" is printed.value is incremented.Again it checks the condition.
(val <= 5). i.e (-4<=5).

"X" is printed repeatedly until value becomes "0".when value is "0"
it Enters into Switch case and "India" is printed.

Then it breaks from the Switch case and Executes.
Else, if statement and prints "B"
Until the value becomes "5".
"B" is printed 5 times.
So, XXXXXIndiaBBBBB is printed, given answer is absolutely right.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.