C# Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - General Questions (Q.No. 6)
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"); 
            break;
    }
    
    if (val > 0)
        Console.Write ("B"); 
    else if (val < 0)
        Console.Write ("X");
}
XXXXXIndia
IndiaBBBBB
XXXXXIndiaBBBBB
BBBBBIndiaXXXXX
Zero
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
6 comments Page 1 of 1.

Sai charan said:   8 years ago
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.
(1)

Sajila said:   1 decade ago
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.

Anusha said:   1 decade ago
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:   1 decade ago
Answer given by India bix is right as break statement make the instruction pointer jump out from the switch {} not from for loop.

Sunshine said:   9 years ago
The answer is indeed C. The break statement breaks out from the switch statement, not from the for loop.

Sneha waghmare said:   10 years ago
The answer is correct given by IndiaBix.

Post your comments here:

Your comments will be displayed after verification.