0
0
Goprogramming~20 mins

Why loops are needed in Go - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Loop Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of a simple for loop in Go
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    for i := 1; i <= 3; i++ {
        fmt.Print(i, " ")
    }
}
A1 2 3
B1 2 3 4
C0 1 2 3
D123
Attempts:
2 left
๐Ÿ’ก Hint
Look at the loop start and end values and what is printed inside the loop.
๐Ÿง  Conceptual
intermediate
1:30remaining
Why use loops instead of repeating code?
Why do programmers use loops instead of writing the same code many times?
ALoops are only used to confuse beginners.
BLoops make the program run slower but look nicer.
CLoops let us repeat actions easily without writing code again and again.
DLoops are used to stop the program from running.
Attempts:
2 left
๐Ÿ’ก Hint
Think about what happens if you want to do the same thing many times.
โ“ Predict Output
advanced
2:30remaining
Output of nested loops in Go
What does this Go program print?
Go
package main
import "fmt"
func main() {
    for i := 1; i <= 2; i++ {
        for j := 1; j <= 2; j++ {
            fmt.Print(i*j, " ")
        }
    }
}
A1 2 3 4
B1 2 2 4
C1 1 2 2
D2 4 2 4
Attempts:
2 left
๐Ÿ’ก Hint
Multiply i and j for each pair in the nested loops.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify the error in this Go loop
What error does this Go code cause?
Go
package main
import "fmt"
func main() {
    for i := 0; i < 3; i++
        fmt.Println(i)
}
ASyntax error: missing semicolon after for statement
BRuntime error: index out of range
CNo error, prints 0 1 2
DSyntax error: missing braces {} around loop body
Attempts:
2 left
๐Ÿ’ก Hint
Check if the loop body is properly enclosed.
๐Ÿš€ Application
expert
2:30remaining
Count how many times a loop runs
How many times does this loop run?
Go
package main
import "fmt"
func main() {
    count := 0
    for i := 10; i > 0; i -= 3 {
        count++
    }
    fmt.Println(count)
}
A4
B6
C5
D3
Attempts:
2 left
๐Ÿ’ก Hint
Start at 10 and subtract 3 each time until i is no longer greater than 0.