Kotlin Subtraction Operator
Kotlin Subtraction Operator returns the subtraction of the right operand from the left operand.
Syntax
The syntax to use Arithmetic Subtraction operator is
n1 - n2
where
n1
is the left operand-
is the symbol used for Subtraction operatorn2
is the right operand
Return Value
The above expression returns the subtraction of the number n2
from the number n1
. The data type of the return value depends on the given values. If given values are of different data types, then the resulting would be the higher data type (data type that can allocate larger memory).
Chaining Subtraction Operator
We can also chain the operator to subtraction more than two numbers from a number, as shown in the following.
n1 - n2 - n3 - n4
The expression return the subtraction of the numbers n2
, n3
, and n4
from the number n1
.
Examples
Subtraction of 4 from 6
In the following program, we take two variables: n1
, and n2
with the values 6
and 4
respectively; and find the subtraction of n2
from n1
.
Kotlin Program
fun main() {
var n1 = 6
var n2 = 4
val result = n1 - n2
println("n1 = $n1\nn2 = $n2\nn1 - n2 = $result")
}
Output
n1 = 6
n2 = 4
n1 - n2 = 2
Subtraction of more than two numbers from a given number
In the following program, we take four integer variables: n1
, n2
, n3
, and n4
, and find the subtraction of the numbers n2
, n3
, and n4
from the number n1
.
Kotlin Program
fun main() {
var n1 = 25
var n2 = 4
var n3 = 2
var n4 = 7
val result = n1 - n2 - n3 - n4
println("n1 - n2 - n3 - n4 = $result")
}
Output
n1 - n2 - n3 - n4 = 12
Subtraction of 3.14 from 2.1
In the following program, we do the subtraction of floating point numbers.
Kotlin Program
fun main() {
var n1 = 3.14
var n2 = 2.1
val result = n1 - n2
println("n1 = $n1\nn2 = $n2\nn1 - n2 = $result")
}
Output
n1 = 3.14
n2 = 2.1
n1 - n2 = 1.04