0
0
Goprogramming~20 mins

Infinite loops in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Infinite Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of a simple infinite loop with break
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
  i := 0
  for {
    if i == 3 {
      break
    }
    fmt.Print(i)
    i++
  }
}
A123
B0123
C012
D0
Attempts:
2 left
๐Ÿ’ก Hint
Look at when the loop stops printing.
โ“ Predict Output
intermediate
2:00remaining
Output of infinite loop with continue
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
  i := 0
  for {
    i++
    if i%2 == 0 {
      continue
    }
    if i > 5 {
      break
    }
    fmt.Print(i)
  }
}
A1357
B12345
C246
D135
Attempts:
2 left
๐Ÿ’ก Hint
Only odd numbers less than or equal to 5 are printed.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify the cause of infinite loop
Why does this Go program run forever without stopping?
Go
package main
import "fmt"
func main() {
  i := 0
  for i < 5 {
    fmt.Print(i)
  }
}
AVariable i is never incremented inside the loop
BThe loop condition is always false
CThe fmt.Print causes the loop to restart
DThe for loop syntax is invalid
Attempts:
2 left
๐Ÿ’ก Hint
Check if the loop variable changes inside the loop.
๐Ÿ“ Syntax
advanced
2:00remaining
Which option causes a compile error due to infinite loop syntax?
Which of these Go loop statements will cause a compile error?
Afor i := 0; i < 5 {}
Bfor i := 0; i < 5; i++ {}
Cfor {}
Dfor i := 0; i < 5; i++ { break }
Attempts:
2 left
๐Ÿ’ก Hint
Check if the for loop header has all three parts separated by semicolons.
๐Ÿš€ Application
expert
2:00remaining
How many times does this infinite loop print?
How many times will the following Go program print "Hello" before stopping?
Go
package main
import "fmt"
func main() {
  count := 0
  for {
    fmt.Println("Hello")
    count++
    if count == 10 {
      break
    }
  }
}
A9
B10
CInfinite times
D0
Attempts:
2 left
๐Ÿ’ก Hint
Look at how count changes and when the break happens.