0
0
Goprogramming~20 mins

Increment and decrement in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Go Increment & Decrement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
}
A3
B0
C1
DSyntax error
Attempts:
2 left
๐Ÿ’ก Hint
Think about how many times the loop runs and how x changes each time.
โ“ Predict Output
intermediate
2: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)
}
A5
B6
C4
DCompilation error
Attempts:
2 left
๐Ÿ’ก Hint
Decrement means subtracting one from the variable.
โ“ Predict Output
advanced
2: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)
}
ACompilation error
B1 1
C2 1
D1 2
Attempts:
2 left
๐Ÿ’ก Hint
Go does not support post-increment as an expression.
โ“ Predict Output
advanced
2: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--
  }
}
ACompilation error
B3 2 1
C3 3 3
D1 2 3
Attempts:
2 left
๐Ÿ’ก Hint
The loop runs while count is greater than zero and decreases count each time.
๐Ÿง  Conceptual
expert
2:00remaining
Why Go disallows increment in expressions
Why does Go language not allow using increment (++) or decrement (--) operators inside expressions like 'b := a++'?
ABecause Go does not support increment or decrement operators at all.
BBecause Go requires ++ and -- to be used only with pointers.
CBecause Go only allows ++ and -- inside function definitions, not in main.
DBecause ++ and -- are statements, not expressions, to avoid confusion and side effects in expressions.
Attempts:
2 left
๐Ÿ’ก Hint
Think about how Go treats ++ and -- differently from some other languages.