0
0
Goprogramming~10 mins

Increment and decrement in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Increment and decrement
Start with variable x
Apply increment x = x + 1
Apply decrement x = x - 1
Use or print x
End
This flow shows starting with a variable, then increasing or decreasing its value by 1, and finally using the updated value.
Execution Sample
Go
package main
import "fmt"
func main() {
  x := 5
  x++
  x--
  fmt.Println(x)
}
This code starts with x=5, increments it by 1, then decrements by 1, and prints the final value.
Execution Table
StepVariable xOperationResultOutput
15Initialize xx = 5
26Increment x++x = 6
35Decrement x--x = 5
45Print xx = 55
💡 Program ends after printing the final value of x which is 5.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
x5655
Key Moments - 2 Insights
Why does x return to 5 after incrementing and then decrementing?
Because increment (x++) adds 1 making x=6, then decrement (x--) subtracts 1 returning x back to 5, as shown in steps 2 and 3 of the execution table.
Does x++ change x immediately or later?
In Go, x++ immediately increases x by 1, as seen in step 2 where x changes from 5 to 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of x after step 2?
A6
B5
C7
D4
💡 Hint
Check the 'Variable x' column in row for step 2 in the execution table.
At which step does x return to its original value?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the variable_tracker and execution_table to see when x changes back to 5.
If we remove the decrement (x--), what would be the output at step 4?
A7
B5
C6
D4
💡 Hint
Consider the variable value after increment only, before printing at step 4.
Concept Snapshot
Increment and decrement in Go:
- Use x++ to add 1 to x
- Use x-- to subtract 1 from x
- Both change x immediately
- Commonly used to update counters
- Final value reflects all increments/decrements
Full Transcript
This example shows how to increase and decrease a variable by 1 in Go. We start with x equal to 5. Then we use x++ to add 1, making x equal to 6. Next, we use x-- to subtract 1, returning x to 5. Finally, we print x, which outputs 5. The execution table tracks each step and the variable's value. Increment and decrement operators change the variable immediately. This is useful for counting or looping.