Question:
How to determine the largest and smallest numbers of an array. How to do it?
Joey
2013-01-17 05:36:29 UTC
So we have an array with a length of 20. Each value is a math.random(). How do you determine the largest integer and the smallest integer without writing 100+ lines of code? Please respond.
Five answers:
John
2013-01-17 05:56:27 UTC
You need two variables and a single loop. Set both variables (say array_max_value and array_min_value) to the first value in your array. Then run a single loop in which you look at each element from the second one to the last in turn. If the element value is larger than array_max_value, set array_max_value equal to the element value. Conversely, if the element value is smaller than array_min_value, set array_min_value equal to the element value.



Conversely, if you are using Javascript which your use of math.random() suggests, than try math.max() and math.min() instead.
Kevin
2013-01-17 05:38:16 UTC
Sort the array. Then, first and last elements are the smallest and largest.
Bullsfan127
2013-01-17 05:42:49 UTC
use a loop



int[20] array;

//populate array



//initialize max o the first element in the array

int max= array[0];



for(int i=0,i<20;i++)

{

if (array[i] > max)

{

max=array[i];

}

}



then you can do pretty much do the opposite for min
Chip
2013-01-17 05:40:01 UTC
Don't know which language you're using, but a lot of them have functions built in that will do that automatically for you. For instance, in Python you can just use min() and max().
Jenica Mae
2013-01-18 04:54:05 UTC
int[] num= new int[20];

for(int i=0;i<20;i++)

{

num[i]=1+(int)(Math.random()*20);

}



int max=num[0];

int min=num[0];

for(int i=1;i<20;i++)

{

if(num[i]>max)

max=num[i];

if(num[i]
min=num[i];

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...