Introduction
Increment and decrement help you add or subtract 1 from a number easily.
Increment and decrement help you add or subtract 1 from a number easily.
variable++ // adds 1 to variable variable-- // subtracts 1 from variable
These operators only add or subtract 1.
They work only with variables, not with constants or expressions.
count := 5 count++ // count becomes 6
score := 10 score-- // score becomes 9
i := 0 for i < 3 { fmt.Println(i) i++ }
This program shows how to increase and then decrease a number by 1.
package main import "fmt" func main() { x := 3 fmt.Println("Start:", x) x++ fmt.Println("After increment:", x) x-- fmt.Println("After decrement:", x) }
Increment (++) and decrement (--) operators are statements in Go, not expressions.
You cannot use them inside other expressions like y = x++.
Use variable++ to add 1.
Use variable-- to subtract 1.
They help count or move step by step in your code.
i++ do in Go?++ operator in Go adds 1 to the variable it is used on.i++ increases the value of i by exactly 1.i++ means add 1 [OK]count by 1 in Go?variable-- is the correct way to subtract 1 from a variable.count--, which is correct. --count is invalid prefix decrement in Go. count++ increases count. count =- 1 is invalid syntax.-- to subtract one [OK]package main
import "fmt"
func main() {
x := 5
x++
x--
x++
fmt.Println(x)
}fmt.Println(x) prints 6.package main
func main() {
var n int = 10
n++
n--
n = n++
}n++ and n-- are statements that increment or decrement n by 1. They cannot be used as expressions.n = n++ tries to use n++ as a value, which is invalid in Go and causes a compile error.for i := 3; i > 0; ??? {
fmt.Println(i)
}i-- decreases i by 1 each loop, matching the goal. Options A, B, and C are wrong: A and B increase i, C is invalid prefix --i in Go.Pass the test and this pattern moves unknown