Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
communitycreator

How to find the sum of elements of an array in Scala

Theodore Kelechukwu Onyejiaku

Overview

We use the while loop to obtain the sum of elements of an array in Scala. The logic is to create an initial sum variable which will be zero. Then in the loop, we will increase this sum with each array element.

Syntax

while(condition){
    // loop body
}
Syntax for a while loop

Parameters

condition: This is a conditional statement. If it returns true, the code body will execute. Otherwise, the code body will not execute.

Example

object Sample {  
    def main(args: Array[String]) {  
        // create an array
        var OurArray = Array(10,20,30,40,50)
        // create a counter
        var counter = 0;
        // create default sum
        var sum = 0;
        
        // create a while loop
        while(counter<OurArray.size) // check if counter is less than array size
        {
            // add element value to sum
            sum = sum + OurArray(counter)
            counter = counter + 1
        }
        
        // print sum of array elements
        printf("Sum of array elements is: %d\n",sum)
    }
}  
The syntax for getting the sum of elements of an array

Explanation

  • Create an array and two integer variables to hold the sum and counter for every loop.
  • Then add the value of array elements to the variable, after accessing and adding all elements to the variable sum. Print the value of the variable on the console screen.

RELATED TAGS

scala
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring