We can easily use the while
loop and integer variables to find the largest number of elements of an array in Scala.
In Scala, the syntax for a while
loop is as follows:
while(condition){// code body}
condition
: This is a conditional statement. If it returns true, the code body will execute. Else, the code body will not execute
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)}
counter
in the loop to keep count of every loop. Use the largest
to obtain the largest number after the loop.while
loop. The code body shall run if the counter
is less than the array size that is 5
as per the condition. if
condition to check if the previous largest
value 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. counter
for every loop. This is so that we can access each element of the array as, OurArray(counter)
.