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.
while(condition){ // loop body }
condition
: This is a conditional statement. If it returns true, the code body will execute. Otherwise, the code body will not execute.
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) } }
sum
and counter
for every loop.sum
. Print the value of the variable on the console screen.RELATED TAGS
CONTRIBUTOR
View all Courses