Introduction
Arithmetic operators in Kotlin are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. These operators are essential for performing calculations in your programs. This chapter will cover the different types of arithmetic operators available in Kotlin, along with examples and their syntax.
Types of Arithmetic Operators
1. +
(Addition)
Adds two values together.
Syntax:
val result = operand1 + operand2
Example:
fun main() {
val a = 10
val b = 5
val sum = a + b
println("Sum: $sum") // Output: Sum: 15
}
2. -
(Subtraction)
Subtracts the second value from the first value.
Syntax:
val result = operand1 - operand2
Example:
fun main() {
val a = 10
val b = 5
val difference = a - b
println("Difference: $difference") // Output: Difference: 5
}
3. *
(Multiplication)
Multiplies two values.
Syntax:
val result = operand1 * operand2
Example:
fun main() {
val a = 10
val b = 5
val product = a * b
println("Product: $product") // Output: Product: 50
}
4. /
(Division)
Divides the first value by the second value.
Syntax:
val result = operand1 / operand2
Example:
fun main() {
val a = 10
val b = 5
val quotient = a / b
println("Quotient: $quotient") // Output: Quotient: 2
}
5. %
(Modulus)
Returns the remainder when the first value is divided by the second value.
Syntax:
val result = operand1 % operand2
Example:
fun main() {
val a = 10
val b = 3
val remainder = a % b
println("Remainder: $remainder") // Output: Remainder: 1
}
Example Program with Arithmetic Operators
Here is an example program that demonstrates the use of various arithmetic operators in Kotlin:
fun main() {
val a = 15
val b = 4
// Addition
val sum = a + b
println("Addition: $sum") // Output: Addition: 19
// Subtraction
val difference = a - b
println("Subtraction: $difference") // Output: Subtraction: 11
// Multiplication
val product = a * b
println("Multiplication: $product") // Output: Multiplication: 60
// Division
val quotient = a / b
println("Division: $quotient") // Output: Division: 3
// Modulus
val remainder = a % b
println("Modulus: $remainder") // Output: Modulus: 3
}
Conclusion
In this chapter, you learned about the various arithmetic operators available in Kotlin, including addition, subtraction, multiplication, division, and modulus. Understanding these operators is crucial for performing mathematical calculations in your Kotlin programs.