0
0
C Sharp (C#)programming~20 mins

Break statement behavior in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Break Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of break in nested loops
What is the output of this C# code snippet?
C Sharp (C#)
using System;
class Program {
  static void Main() {
    for (int i = 1; i <= 3; i++) {
      for (int j = 1; j <= 3; j++) {
        if (j == 2) break;
        Console.Write(i * 10 + j + " ");
      }
    }
  }
}
A11 21 22 31 32
B11 12 21 22 31 32
C11 12 13 21 22 23 31 32 33
D11 21 31
Attempts:
2 left
💡 Hint
Remember that break exits only the innermost loop.
Predict Output
intermediate
1:30remaining
Break inside switch statement
What will this C# program print?
C Sharp (C#)
using System;
class Program {
  static void Main() {
    int x = 2;
    switch (x) {
      case 1:
        Console.Write("One");
        break;
      case 2:
        Console.Write("Two");
        break;
      default:
        Console.Write("Default");
        break;
    }
  }
}
AOne
BTwo
CDefault
DOneTwo
Attempts:
2 left
💡 Hint
The break in switch stops fall-through to other cases.
Predict Output
advanced
2:00remaining
Break effect in while loop with continue
What is the output of this C# code?
C Sharp (C#)
using System;
class Program {
  static void Main() {
    int i = 0;
    while (i < 5) {
      i++;
      if (i == 3) break;
      if (i == 2) continue;
      Console.Write(i + " ");
    }
  }
}
A1
B1 2
C1 3
D1 4
Attempts:
2 left
💡 Hint
Note that continue skips printing when i == 2, and break stops loop at i == 3.
🔧 Debug
advanced
1:30remaining
Identify error with break outside loop
What error does this C# code produce?
C Sharp (C#)
using System;
class Program {
  static void Main() {
    int x = 5;
    if (x > 3) {
      break;
    }
    Console.WriteLine("Done");
  }
}
ANo error, prints "Done"
BRuntime error: InvalidOperationException
CSyntax error: 'break' not inside loop or switch
DCompilation warning only
Attempts:
2 left
💡 Hint
Break can only be used inside loops or switch statements.
Predict Output
expert
2:30remaining
Break with labeled loops simulation
What is the output of this C# code simulating labeled break behavior?
C Sharp (C#)
using System;
class Program {
  static void Main() {
    bool exitOuter = false;
    for (int i = 1; i <= 3; i++) {
      for (int j = 1; j <= 3; j++) {
        if (i * j > 3) {
          exitOuter = true;
          break;
        }
        Console.Write(i * 10 + j + " ");
      }
      if (exitOuter) break;
    }
  }
}
A11 12 13 21
B11 12 13 21 22 23
C11 12 13 21 22 23 31 32 33
D11 12 21 22 23
Attempts:
2 left
💡 Hint
The inner break stops inner loop, the flag triggers break of outer loop.