Scala

33 / 53

Scala - Assessment - Function to calculate sum of consecutive numbers

A function is a reusable component of a program which optionally takes some input parameters or arguments and performs some actions based on those parameters.

We will write a simple Scala program with a singleton object named Calc which will have a function named calcSum. This function takes 2 numbers as arguments and calculates the sum of all numbers between these 2 numbers including these 2 numbers.

For example: Executing Calc.calcSum(5,8) will calculate sum of numbers 5,6,7,8 which is 5 + 6 + 7 + 8 = 26.

INSTRUCTIONS
  • Switch to the Jupyter tab.

  • Write the code of the class. The program's main singleton class name will be Calc and it will have a function named calcSum.

The program code would be like:

    object Calc {
       def calcSum( x:Int, y:Int ) : Int = {
      ....
  • Press Shift + Enter to execute the code.

  • Check that you are able to run Calc.calcSum(5,8) in Jupyter and that you are getting the expected result with some more test cases.

  • Click on "Submit Answer".



Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...