How To Find The Sum Of Elements Of An Array In Scala

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeHow to find the sum of elements of an array in Scala

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) }} Run

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.

Relevant Answers

Explore Courses

Free Resources

License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)

Tag » Add Element List Scala