Learn
Using Number Variables
Increment and Decrement Operators

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, ++:

variableName++  

The decrement operator represents the subtraction of 1 from a variable using two consecutive minus operators, --:

variableName--  

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

Note: ++ and += 1 are the same operations and can be used interchangeably throughout a program.

Instructions

1.

In Challenge.kt, we’ve set up variables, a, b, c, and d to hold numerical values or expressions. Use your knowledge of shorthand arithmetic operators to determine the final value of d.

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.

Folder Icon

Take this course for free

Already have an account?