Continue & Break

Whenever we want to change the control flow of a loop we can use the continue and break keywords.

continue

The continue keyword stops the current iteration of a loop and continues to the next iteration. continue is a powerful way to use the guard clausearrow-up-right pattern within loops.

for i := 0; i < 10; i++ {
  if i % 2 == 0 {
    continue
  }
  fmt.Println(i)
}
// 1
// 3
// 5
// 7
// 9

break

The break keyword stops the current iteration of a loop and exits the loop.

for i := 0; i < 10; i++ {
  if i == 5 {
    break
  }
  fmt.Println(i)
}
// 0
// 1
// 2
// 3
// 4

Assignment

As an Easter egg, we decided to reward our users with a free text message if they send a prime numberarrow-up-right of text messages this year.

Complete the printPrimes function. It should print all of the prime numbers up to and including max. It should skip any numbers that are not prime.

Here's the pseudocode:

  • We skip even numbers because they can't be prime

  • We only check up to the square root of n. A factor higher than the square root of n must multiply with a factor lower than the square root of n, meaning we only need to check up to the square root of n for potential factors.

    • In your code, you can set the stop condition as i * i <= n

  • We start checking at 2 because 1 is not prime

This lesson is graded based on the output of your program, so don't leave any debugging print statements in your code.

Example Output

For the first test case, prime number up to 10:

We only want you to print the numbers themselves, not the headings and delimiter, they are already handled for you in the test code.

πŸ”’ Prime Numbers with continue and break β€” Go

Problem

Print all prime numbers up to and including max.

  • Start checking from 2 (1 is not prime)

  • Skip even numbers (except 2)

  • Only check divisors up to √n

  • Use continue to skip non-prime numbers

  • Use break to stop checking once a divisor is found


Key Go Concepts Used

  • for loops

  • continue (skip current iteration)

  • break (exit inner loop early)

  • Modulo operator %

  • Boolean flags for control flow

  • fmt.Println() for output


Solution

Why This Works

  • continue skips even numbers early (guard clause pattern)

  • i * i <= n avoids calling math.Sqrt and limits divisor checks

  • break exits the inner loop as soon as a factor is found

  • Each number is printed exactly once