In addition to augmented assignment operators, Kotlin provides us with two arithmetic shortcuts that can be used to perform quick addition and subtraction calculations. These are known as increment and decrement operators.
An increment operator represents the addition of
1 to a variable using two consecutive plus operators,
The decrement operator represents the subtraction of
1 from a variable using two consecutive minus operators,
This shorthand syntax is most useful with loops and conditionals - concepts we’ll explore later in this course. For now, let’s just get familiar with the syntax.
Assume we’re writing a program that keeps track of how many apples we have in our basket whilst apple picking. 🍎
var apples = 5
We picked up a Gala apple, so let’s add
1 to our basket using an increment operator:
apples++ println(apples) // Prints: 6
We ate a Honey Crisp apple from our basket, so let’s subtract
1 from the total:
apples-- println(apples) // Prints: 5
+= 1 are the same operations and can be used interchangeably throughout a program.
In Challenge.kt, we’ve set up variables,
d to hold numerical values or expressions. Use your knowledge of shorthand arithmetic operators to determine the final value of
Store your answer in a single line comment when you’re ready as so:
// d: some value
Refrain from using a print statement to get the answer. Instead, check the hint for a breakdown of the solution when you’re ready.