Challenge - 5 Problems
Go Increment & Decrement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of increment in a loop
What is the output of this Go program?
package main
import "fmt"
func main() {
x := 0
for i := 0; i < 3; i++ {
x++
}
fmt.Println(x)
}Go
package main import "fmt" func main() { x := 0 for i := 0; i < 3; i++ { x++ } fmt.Println(x) }
Attempts:
2 left
๐ก Hint
Think about how many times the loop runs and how x changes each time.
โ Incorrect
The loop runs 3 times, and each time x is increased by 1 using x++. So final x is 3.
โ Predict Output
intermediate2:00remaining
Decrement operator effect
What will this Go program print?
package main
import "fmt"
func main() {
y := 5
y--
fmt.Println(y)
}Go
package main import "fmt" func main() { y := 5 y-- fmt.Println(y) }
Attempts:
2 left
๐ก Hint
Decrement means subtracting one from the variable.
โ Incorrect
y starts at 5, then y-- subtracts 1, so y becomes 4.
โ Predict Output
advanced2:00remaining
Increment in expression
What is the output of this Go code?
package main
import "fmt"
func main() {
a := 1
b := a++
fmt.Println(a, b)
}Go
package main import "fmt" func main() { a := 1 b := a++ fmt.Println(a, b) }
Attempts:
2 left
๐ก Hint
Go does not support post-increment as an expression.
โ Incorrect
In Go, the increment operator ++ is a statement, not an expression. So 'b := a++' causes a compilation error.
โ Predict Output
advanced2:00remaining
Decrement in a for loop
What does this Go program print?
package main
import "fmt"
func main() {
count := 3
for count > 0 {
fmt.Print(count, " ")
count--
}
}Go
package main import "fmt" func main() { count := 3 for count > 0 { fmt.Print(count, " ") count-- } }
Attempts:
2 left
๐ก Hint
The loop runs while count is greater than zero and decreases count each time.
โ Incorrect
The loop prints count starting at 3, then 2, then 1, then stops when count is 0.
๐ง Conceptual
expert2:00remaining
Why Go disallows increment in expressions
Why does Go language not allow using increment (++) or decrement (--) operators inside expressions like 'b := a++'?
Attempts:
2 left
๐ก Hint
Think about how Go treats ++ and -- differently from some other languages.
โ Incorrect
Go treats ++ and -- as statements to keep code clear and avoid subtle bugs from side effects in expressions.