What will be the output of the following C#.NET code? 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"); }

Difficulty: Medium

Correct Answer: XXXXXIndiaBBBBB

Explanation:


Introduction / Context:
The snippet mixes switch and if/else to print characters across a numeric range. We must track control flow for negative, zero, and positive values.



Given Data / Assumptions:

  • Loop variable val goes from -5 to 5 inclusive.
  • At val == 0, the program prints "India".
  • For val > 0, it prints "B"; for val < 0, it prints "X".


Concept / Approach:
Count how many times each branch fires: negatives produce X, zero prints India, positives produce B.



Step-by-Step Solution:

Values -5, -4, -3, -2, -1 → five negatives → prints "X" five times.Value 0 → matches case 0 → prints "India".Values 1, 2, 3, 4, 5 → five positives → prints "B" five times.Concatenate in loop order: "XXXXX" + "India" + "BBBBB".


Verification / Alternative check:
Mental simulation or quick run confirms the exact sequence.



Why Other Options Are Wrong:

  • XXXXXIndia: Missing the positive portion.
  • IndiaBBBBB: Missing the negative portion.
  • BBBBBIndiaXXXXX: Wrong order.
  • Zero: Not printed anywhere.


Common Pitfalls:
Assuming if/else executes before switch or miscounting loop bounds.



Final Answer:
XXXXXIndiaBBBBB

More Questions from Control Instructions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion