# Finding a number in array close to another number

Printable View

• 02-15-2010, 12:54 AM
SteroidalPsycho
Finding a number in array close to another number
I am having trouble coming up with a method that will take an array of doubles and find the number in the array closest to the average of the array. I know how to make a for loop to find the average but I don't know how to implement a method that will find the double in the array closest to the average. How (in pseudo code) would I implement this?
• 02-15-2010, 01:03 AM
collin389
You could have two variables: double distance, and int index = 0. then loop through your array and compute the distance away from the average: (distance = Math.abs(average - array[i]) then the next time check if the distance of that number is less than the stored distance. If it is less, then store it's distance to the var distance, and its index to var index. If it is greater, go to next number in the array( continue;)
Hope this helped.
• 02-15-2010, 01:37 AM
SteroidalPsycho
Yes thanks a lot! I really appreciate your time!