+ 1
While finding maximum and minimum element in an array why do we initialise max=0 and min=ar[0] ?
4 ответов
+ 3
The algorithm iterates the array and compares each el to current max,min.
We must have an initial value of max,min for comparing first el.
There is more than one opportunity to do that initialization.
Task for you:
Does it work if max is ar[0]?
Does it work with min = 0?
Play around with it...
+ 3
+ 1
Because we are pretty sure that the largest will be greater than 0 in most cases. Initializing max to any other value for example 100 will only help you compare the values greater than 100 which might skip some of the elements or you might not even find any that is greater than 100 in the given array.
0
The code works for min=0
But while initialising max=ar[0] the output is wrong