1. Introduction
Arithmetic operators are fundamental tools in programming languages used to perform mathematical operations. Scala, being a language that supports both object-oriented and functional programming paradigms, has a rich set of arithmetic operators. In this blog post, we'll discuss and demonstrate the use of arithmetic operators in Scala.
Scala - Arithmetic Operators
Scala supports the following arithmetic operators:
+ (Addition): Adds values on either side of the operator.
- (Subtraction): Subtracts the right-hand operand from the left-hand operand.
* (Multiplication): Multiplies values on either side of the operator.
/ (Division): Divides the left-hand operand by the right-hand operand.
% (Modulus): Divides the left-hand operand by the right-hand operand and returns the remainder.
2. Program Steps
1. Define variables with numerical values.
2. Perform arithmetic operations using the operators.
3. Print the results of these operations.
4. Execute the program to verify the outputs.
3. Code Program
object ArithmeticOperatorsDemo extends App {
// Define numerical values
val a: Int = 10
val b: Int = 5
// Addition
val sum: Int = a + b
// Subtraction
val diff: Int = a - b
// Multiplication
val product: Int = a * b
// Division
val quotient: Int = a / b
// Modulus
val remainder: Int = a % b
// Print the results
println(s"Addition: $a + $b = $sum")
println(s"Subtraction: $a - $b = $diff")
println(s"Multiplication: $a * $b = $product")
println(s"Division: $a / $b = $quotient")
println(s"Modulus: $a % $b = $remainder")
}
Output:
Addition: 10 + 5 = 15 Subtraction: 10 - 5 = 5 Multiplication: 10 * 5 = 50 Division: 10 / 5 = 2 Modulus: 10 % 5 = 0
Explanation:
1. We have declared two integer variables a and b with the values 10 and 5, respectively.
2. We have performed basic arithmetic operations: addition, subtraction, multiplication, division, and modulus using the Scala arithmetic operators.
3. We stored the results of these operations in respective variables: sum, diff, product, quotient, and remainder.
4. Each result is then printed to the console with a descriptive message.
5. The output demonstrates the results of the arithmetic operations. For instance, when we add 10 and 5 using the + operator, we get 15, and similarly, for other operations.
Comments
Post a Comment