Start learning free

LESSON 16 OF 348 · CALCULATIONS WITH NUMBERS

Arithmetic Operators in Scala in Scala

Lesson

TL ; DR:

  • We can tell computers to perform calculations for us using +, -, *, /:

    println(2 + 6) // Prints 8
    println(10 - 7) // Prints 3
    println(3 * 3) // Prints 9
    println(6 / 2) // Prints 3
    


  • We can also use variables. In these examples, Scala will replace variable num with its value 6 to do the calculations:

    var num = 6
    println(num + 5) // Prints 11
    println(10 - num) // Prints 4
    println(3 * num) // Prints 18
    println(num / 2) // Prints 3
    



Full lesson:

Computers absolutely excel at performing calculations. The "compute" in their name comes from their historical association with providing answers to mathematical questions.

These calculations can be performed either directly with numbers or with variables that are assigned numeric values.

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Examples
+ Addition 3 + 5,  x + 5,  3 + y,  x + y
- Subtraction 8 - 3,  8 - y,  x - 3,  x - y
* Multiplication 3 * 5,  3 * y,  x * 5,  x * y
/ Division 8 / 4,  8 / y,  x / 8,  x / y
% Modulus 8 % 4,   8 % y,  x % 4,  x % y


Note that performing arithmetic on variables does not change the variable - you can only update a variable using the = sign.

Let's go through some examples together to better understand how each operator works:


Addition

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(a + b) // Output: 5

println(a + 10) // Output: 12

Subtraction

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(a - b) // Output: -1

println(10 - b) // Output: 7

Multiplication

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(a * 5) // Output: 10

println(2 * a * b) // Output: 12

Division

In Scala, division between integers returns only the integral part of the result:

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println(20 / 3) // Output: 6

println(b / a) // Output: 1

If we want to get the real result of the division, at least one of the terms has to be of type "Double":

// Declare 2 integer variables and initialize them:
var a = 2
var b = 3

println((Double) 7 / 3) // Output: 2.5

println(b / (Double) a) // Output: 1.5

Assignment
Follow the Coding Tutorial and let's practice with arithmetic operators!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    Arithmetic Operators in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free