-2

Ok so i have to do this: Stretch #2: W​rite a loop that iterates through the array named v​alues​and finds the largest number in the array. Place the value into the variable m​aximum. ​

I tired not doing it with a loop, but by :

{


    if values[1] > values[0]
    {
      maximum = values[1]
    }
    else if values[2] > values[1]
    {
        maximum = values[2]

    }
    else if values[3] > values[2]
    {
        maximum = values[3]
    }
    else if values[4] > values[3]
    {
        maximum = values[4]
    }


    }

That didn't work and I don't know what to do.

  • Possible duplicate of [Correct way to find max in an Array in Swift](http://stackoverflow.com/questions/24036514/correct-way-to-find-max-in-an-array-in-swift) – Marcos Griselli Dec 18 '15 at 16:38

1 Answers1

1

Your code uses an if - else chain rather than a loop which is pretty long-winded and annoying for a large amount of items.

You're probably looking for this:

var maximum = 0
for aValue in values {
    if aValue > maximum {
       maximum = aValue
    }
}

If the array doesn't contain integer values set the variable maximum to the appropriate type.

vadian
  • 274,689
  • 30
  • 353
  • 361