The Modulo Operator
Part of the Fundamentals section of Coddy's GO journey — lesson 17 of 109.
The modulo operator (%) returns the remainder after division of one number by another.
Calculate the remainder when dividing 10 by 3:
a := 10
b := 3
remainder := a % b
fmt.Println(remainder)Output:
1This is useful for determining if a number is even or odd:
number := 15
isEven := number % 2 == 0
fmt.Println("Is", number, "even?", isEven)Output:
Is 15 even? falseChallenge
BeginnerIn this challenge, you'll practice using the modulo operator (%) in Go. The modulo operator returns the remainder after division.
We have two numbers already defined. Your task is to calculate the remainder when number is divided by divisor using the modulo operator, and store it in the remainder variable.
Cheat sheet
The modulo operator (%) returns the remainder after division of one number by another.
a := 10
b := 3
remainder := a % b
fmt.Println(remainder) // Output: 1Useful for determining if a number is even or odd:
number := 15
isEven := number % 2 == 0
fmt.Println("Is", number, "even?", isEven) // Output: Is 15 even? falseTry it yourself
package main
import "fmt"
func main() {
// These variables are already defined for you
number := 17
divisor := 5
// TODO: Calculate the remainder when 'number' is divided by 'divisor'
// using the modulo operator (%) and store it in the 'remainder' variable
var remainder int
// This will print the result
fmt.Println("The remainder when", number, "is divided by", divisor, "is:", remainder)
}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