Scala program to calculate the sum of array elements

Here, we are going to learn how to calculate the sum of array elements in Scala programming language?
Submitted by Nidhi, on May 07, 2021 [Last updated : March 10, 2023]

Scala – Finding the Sum of Array Elements

Here, we will create an array of integer elements, and then we will calculate the sum of array elements and print the result on the console screen.

Scala code to find the sum of array elements

The source code to calculate the sum of array elements is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to calculate the 
// sum of array elements

object Sample {  
    def main(args: Array[String]) {  
        var IntArray = Array(10,20,30,40,50)
        var count:Int=0
        var sum:Int=0
        
        while(count<IntArray.size)
        {
            sum =sum + IntArray(count)
            count=count+1
        }
        
        printf("Sum of array elements is: %d\n",sum)
    }
}  

Output

Sum of array elements is: 150

Explanation

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

In the main() function, we created a array IntArr and two integer variables count, sum. Then we added the value of array elements to the sum variable. After accessing and adding all elements to the sum variable. We printed the value of the sum variable on the console screen.

Scala Array Programs »



Related Programs



All Scala Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.