function advice

Hey everyone,

So I made a 2d array. I have to find the lowest, highest, and average. Which I got that, but didn't really did it efficient in my opinion. I did the nested loops for the lowest, highest, and average. Obviously the nested loops for each are some what similar but different. I think it would be better to create a function somehow the nested loops. Would you experienced programmers thinks its better or just leave it alone?
Probably doesn't matter that much. It's a bit inefficient since you're going through all the elements.

Ways to make it better would be, if you're filling the array yourself, you can keep track of the minimum and maximum numbers you put in. If the 2D array is filled in some kind of order, you can make use of that so you search through less elements.

Overall, I wouldn't worry about it.
Efficiency aside, why is the array 2D if the dimensions of the array are meaningless (you're iterating through it in a purely linear fashion)?

I think it would be better to create a function somehow the nested loops.
What?

You could combine the three operations as you iterate.
1
2
3
4
5
6
7
8
9
10
11
12
13
for (iterate through each element of array)
{
    if (element > max so far)
        max so far = element;

    if (element < min so far)
        min so far = element;

    sum += element
}
max = max so far
min = min so far
average = sum / num_elements;
Last edited on
Topic archived. No new replies allowed.