Arithmetic Operators
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 19 of 93.
Kotlin provides arithmetic operators to perform mathematical calculations on numbers. These are the same operators you'd use in basic math.
Here are the four fundamental arithmetic operators:
| Operator | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | Division | 10 / 3 | 3 |
You can use these operators with variables and store results:
fun main() {
val a = 15
val b = 4
val sum = a + b // 19
val difference = a - b // 11
val product = a * b // 60
val quotient = a / b // 3
println(quotient)
}Important: When dividing two integers, Kotlin performs integer division: the result is truncated, not rounded. So 15 / 4 gives 3, not 3.75.
If you need decimal results, at least one number must be a Double:
fun main() {
println(15.0 / 4) // Prints: 3.75
}Challenge
EasyYou are provided with the following variables:
val x = 24
val y = 7Using these variables, calculate and print the following on separate lines:
- The sum of
xandy - The difference when
yis subtracted fromx - The product of
xandy - The result of dividing
xbyy(integer division)
Remember: Integer division truncates the decimal part, so the last result will be a whole number.
Try it yourself
fun main() {
val x = 24
val y = 7
// TODO: Write your code below
// Calculate and print:
// 1. The sum of x and y
// 2. The difference when y is subtracted from x
// 3. The product of x and y
// 4. The result of dividing x by y (integer division)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground