Challenge - 5 Problems
Go For Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of a for loop used as while
What is the output of this Go program that uses a for loop as a while loop?
Go
package main import "fmt" func main() { i := 0 for i < 3 { fmt.Print(i) i++ } }
Attempts:
2 left
๐ก Hint
Remember that the loop runs while the condition is true and increments i each time.
โ Incorrect
The loop starts with i=0 and runs while i<3. It prints i each time without spaces, so output is '012'.
โ Predict Output
intermediate2:00remaining
Counting down with for loop as while
What does this Go code print?
Go
package main import "fmt" func main() { i := 3 for i > 0 { fmt.Print(i) i-- } }
Attempts:
2 left
๐ก Hint
The loop decreases i from 3 down to 1, printing each value.
โ Incorrect
The loop prints i starting at 3 and decreases until i is 0 (not printed). Output is '321'.
๐ง Debug
advanced2:00remaining
Identify the error in for loop as while
What error does this Go code produce?
Go
package main import "fmt" func main() { i := 0 for i < 3 { fmt.Println(i) } }
Attempts:
2 left
๐ก Hint
Check if the loop variable changes inside the loop.
โ Incorrect
The variable i is never incremented, so the condition i < 3 is always true, causing an infinite loop.
๐ง Conceptual
advanced2:00remaining
Understanding for loop as while syntax
Which of these Go for loops correctly acts like a while loop that runs while x is less than 5?
Attempts:
2 left
๐ก Hint
Remember the syntax for a for loop with only a condition in Go.
โ Incorrect
Option A uses a condition only and is valid syntax for a for loop acting as a while loop. Option A is invalid syntax. Option A is a classic for loop with init, condition, and post. Option A is invalid syntax.
๐ Application
expert2:00remaining
Predict the final value after for loop as while
What is the value of variable sum after running this Go code?
Go
package main import "fmt" func main() { sum := 0 i := 1 for i <= 5 { sum += i i += 2 } fmt.Println(sum) }
Attempts:
2 left
๐ก Hint
Add 1, then 3, then 5 to sum.
โ Incorrect
The loop adds i to sum while i <= 5. i takes values 1, 3, 5. Sum is 1+3+5=9.