0
0
Goprogramming~5 mins

Increment and decrement in Go

Choose your learning style9 modes available
Introduction

Increment and decrement help you add or subtract 1 from a number easily.

Counting items in a list one by one.
Moving forward or backward in a loop.
Tracking how many times something happens.
Adjusting a score or value step by step.
Syntax
Go
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.

Examples
This adds 1 to count.
Go
count := 5
count++  // count becomes 6
This subtracts 1 from score.
Go
score := 10
score--  // score becomes 9
Increment i in a loop to count from 0 to 2.
Go
i := 0
for i < 3 {
    fmt.Println(i)
    i++
}
Sample Program

This program shows how to increase and then decrease a number by 1.

Go
package main

import "fmt"

func main() {
    x := 3
    fmt.Println("Start:", x)
    x++
    fmt.Println("After increment:", x)
    x--
    fmt.Println("After decrement:", x)
}
OutputSuccess
Important Notes

Increment (++) and decrement (--) operators are statements in Go, not expressions.

You cannot use them inside other expressions like y = x++.

Summary

Use variable++ to add 1.

Use variable-- to subtract 1.

They help count or move step by step in your code.