What is the output of the following C# code?
int x = 7; if (x > 5) { if (x < 10) { Console.WriteLine("A"); } else { Console.WriteLine("B"); } } else { Console.WriteLine("C"); }
Check the conditions step by step starting from the outer if.
The variable x is 7, which is greater than 5, so the outer if is true. Then the inner if checks if x is less than 10, which is also true. So it prints "A".
What will be printed when this code runs?
string color = "red"; if (color == "blue") { Console.WriteLine("Blue selected"); } else { if (color == "red") { Console.WriteLine("Red selected"); } else { Console.WriteLine("Other color"); } }
Check the value of the variable and the conditions carefully.
The variable color is "red", so the first if condition is false. The else block runs, and inside it the inner if checks if color is "red", which is true, so it prints "Red selected".
What error will this C# code produce when compiled?
int n = 3; if (n > 0) if (n < 5) Console.WriteLine("In range"); else Console.WriteLine("Out of range"); else Console.WriteLine("Negative"); else Console.WriteLine("Zero");
Look carefully at the placement of else statements and braces.
The code has two else statements at the same indentation level but only one if to match. This causes a syntax error: 'else' without a matching 'if'.
What is the output of this code snippet?
int score = 85; if (score >= 90) { Console.WriteLine("Grade A"); } else { if (score >= 80) { Console.WriteLine("Grade B"); } else { Console.WriteLine("Grade C"); } }
Check the score against each condition carefully.
The score is 85, which is not >= 90, so the first if is false. The else block runs, and inside it the inner if checks if score >= 80, which is true, so it prints "Grade B".
Consider this nested if-else structure:
if (A)
{
if (B)
{
Action1;
}
else
{
Action2;
}
}
else
{
Action3;
}Which statement is true about when Action2 executes?
Trace the conditions that lead to the else inside the first if.
Action2 is inside the else of the inner if (B). It runs only if A is true (outer if) and B is false (inner else).