How to find the largest number in an array in Scala
Overview
We can easily use the while loop and integer variables to find the largest number of elements of an array in Scala.
Syntax
In Scala, the syntax for a while loop is as follows:
while(condition){// code body}
Syntax for the while loop
Parameters
condition: This is a conditional statement. If it returns true, the code body will execute. Else, the code body will not execute
Code
Here's an example of finding the largest element in an array.
object Main extends App {// create default variablesvar OurArray = Array(1, 5, 4, 2, 3)var counter = 0var largest = 0// create a while loopwhile(counter < OurArray.size) // if less than size of array{if(largest < OurArray(counter))// make current element largestlargest = OurArray(counter)// increase counter after every loopcounter = counter + 1}// after the loop print highest valueprintln("The highest value is "+largest)}
Explanation
- Lines 3–5: Create an array and two variables. Use
counterin the loop to keep count of every loop. Use thelargestto obtain the largest number after the loop. - Line 8: Creates a
whileloop. The code body shall run if thecounteris less than the array size that is5as per the condition. - Line 10: We use an
ifcondition to check if the previouslargestvalue is less than the array element. If so, then the largest becomes that array element. This is how the code will run until we obtain the largest element. - Line 15: Increase the
counterfor every loop. This is so that we can access each element of the array as,OurArray(counter). - Line 19: Prints the largest element.