'Average from an array?

Task description:

The Dutch conquer territory from the sea with dams and do not like to be crossed by these dams the waves. The renovation of an old dam is planned as follows. A is measured at a point in front of the dam the height of the waves and then take the waves that strike (i.e., those that are higher than the at the current dam) and the average height of these waves will be the new dam height. For example, if you have one 20-meter dam, and waves [12, 32, 16, 40, 21] meters high are measured in front of it, then the 2nd, 4th, and 5th pins, their values ​​are 32, 40, 21, the average of which is (32 + 40 + 21) / 3 = 31, ie the new dam must be 31 meters. Write a function that calculates the new dam height. The first input parameter is a whole a standing array whose terminating element is 0. This contains the height of the waves. The other input parameter is current dam height, which is an integer. The function is the integer part of the average of the waves higher than the barrier returns. If no waves pass, the function returns the height of the original dam. int average (int input [], int height);

My code is:

int average(int input[], int height){
    int counter = 0;
    int added = 0;
    int average;

    for(int i = 0; input[i] != '0'; i++)
        if(input[i]>height) {
            added += input[i];
            counter++;
        }

    average = added/counter;

    return average;
}

The problem is that when I run the code, I got this error message:

Process finished with exit code -1073741819 (0xC0000005)

I've looked into this for unauthorized memory usage, but I can't figure out what's causing this.

I got the answer thanks to you guys.:

if (counter != 0) {
        average = added / counter;
        return average;
    } else {
        return height;
    }

That's it, my problem was dividing by 0.



Solution 1:[1]

The array has whats called a sentinel value. Ie a special value that marks the end. It is a value of 0. But you are not testing for it correctly

   for(int i = 0; input[i] != '0'; i++)

you mean

   for(int i = 0; input[i] != 0; i++)

why?

In C '0' is a character. Characters will be treated as integers in almost all placed where an integer is expected. But it is a direct translation of the ASCII value of the character. See here https://www.asciitable.com/

You see that the character '0' is actually decimal 48, hex 0x32, not 0.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pm100