While finding maximum and minimum element in an array why do we initialise max=0 and min=ar[0] ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

While finding maximum and minimum element in an array why do we initialise max=0 and min=ar[0] ?

12th Mar 2020, 7:45 AM
Somya Priyadarshini
Somya Priyadarshini - avatar
4 Answers
+ 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...
12th Mar 2020, 7:55 AM
Oma Falk
Oma Falk - avatar
12th Mar 2020, 8:07 AM
Oma Falk
Oma Falk - avatar
+ 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.
12th Mar 2020, 7:51 AM
Avinesh
Avinesh - avatar
0
The code works for min=0 But while initialising max=ar[0] the output is wrong
12th Mar 2020, 8:07 AM
Somya Priyadarshini
Somya Priyadarshini - avatar