Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need a function in Swift to: Find the largest number from numbers and then pri

ID: 3672111 • Letter: I

Question

I need a function in Swift to:

Find the largest number from numbers and then print it. Use reduce to solve this exercise. let numbers = [4, 7, 1, 9, 6, 5, 6, 9]

The reduce method solves the problem of combining the elements of an array to a single value In Swift reduce is declared as a method on the Array class with signature func reduce(initial: U, combine: (U, T) -> U) -> U i.e. receives an initial element of type U and a function that specifies how to combine an element of type U with an element of type T to a single element of type U. The whole array is reduced to a single element of type U

To compute the sum of our array we can use:

sum = moneyArray.reduce(0,{$0 + $1})

In our example both U and T are of type Int, the initial element is 0 and the combine function is adding two Ints

Explanation / Answer

Answer:

//Array of numbers
var numbers=[4, 7, 1, 9, 6, 5, 6, 9]
//function call
var large=largest(numbers)

//function to find largest nunber in an array
// The number which provides, smallest sum
//in its absence , is largest number
func largest(numbers: [Int]) -> Int {
   var sum=0
   var max=0
   var position
   for (index, number) in enumerate(number)
       {
       // sum of elements , except particular index
       sum=numbers.reduce(index,{$0+$1}
       //if sum is smaller than max, replace max by sum
       //store the corresponding index
       if sum<max{
           max=sum
           position=index
           }
       sum=0
       }
// display largest number
   print("largest Number : (numbers[position])")
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote