Increment and Decrement
Part of the Fundamentals section of Coddy's GO journey — lesson 20 of 109.
Increment and decrement operators provide a shorthand way to add or subtract 1 from a variable.
Go uses ++ to increment and -- to decrement a variable by 1:
count := 5
count++ // Same as: count = count + 1
fmt.Println(count)
count-- // Same as: count = count - 1
fmt.Println(count)Output:
6
5Important: In Go, ++ and -- are statements, not expressions. They can only be used as standalone lines, not within other expressions.
Challenge
BeginnerIn this challenge, you'll practice using increment (++) and decrement (--) operators in Go.
We have a variable counter with an initial value. Your task is to:
- Increment the counter twice using the
++operator - Decrement the counter once using the
--operator
The program will then print the final value of the counter.
Cheat sheet
Go uses ++ to increment and -- to decrement a variable by 1:
count := 5
count++ // Same as: count = count + 1
count-- // Same as: count = count - 1Important: In Go, ++ and -- are statements, not expressions. They can only be used as standalone lines, not within other expressions.
Try it yourself
package main
import "fmt"
func main() {
// Starting value for our counter
counter := 5
// TODO: Increment counter twice using the ++ operator
// TODO: Decrement counter once using the -- operator
// Print the final value
fmt.Println("Final counter value:", counter)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions