Scala - Arithmetic Operators



Scala arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, division, and modulus (remainder). The following arithmetic operators are supported by Scala language: + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). For example, let us assume variable A holds 10 and variable B holds 20, then −

Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by denominator B / A will give 2
% Modulus operator finds the remainder after division of one number by another B % A will give 0

Example of Scala Arithmetic Operators

Consider the following example program to understand all the arithmetic operators available in Scala −

object Demo {
   def main(args: Array[String]) = {
      var a = 10;
      var b = 20;
      var c = 25;
      var d = 25;
      
      println("a + b = " + (a + b) );
      println("a - b = " + (a - b) );
      println("a * b = " + (a * b) );
      println("b / a = " + (b / a) );
      println("b % a = " + (b % a) );
      println("c % a = " + (c % a) );
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

a + b = 30
a - b = -10
a * b = 200
b / a = 2
b % a = 0
c % a = 5
Advertisements