# A logic error in my program

• 09-04-2012
20120903
A logic error in my program
Code:

```/*To find out the value in the array that the sum of all elements of the same number is the largest*/ /* Can anyone tell me what the logic error is? Thanks. */ int findMaxValue(int arr[], int n){ //n = number of elements in array     int ans=0;     int maxValue = 0;     int temp[80]; //maximum of array lenth is 80     int i,j;         for(i=0; i<n; i++){         for(j=1; j<100; j++){ //the value in array is from 0 to 100             if(arr[i] ==  j)                 temp[j] += j;         }     }     for (j=1; j<100; j++){         if(temp[j] > maxValue){             maxValue = temp[j];             ans = j;         }     }     return ans; } //Thank you.```
• 09-04-2012
Welcome to the forum, 20120903! :cool:

7 three's, 3 sixes, and 2 ten's, you want the program to calculate that it's the 7 three's that have the greatest value, right?

I don't see logic for that. Maybe:

in an array, count up how many of each number, you have:
Code:

```for(i=0;i<n;i++)   array[array[i]]++;```
Which just tells you you have X number of three's, and Y number of four's, etc. (Obviously, this is bogus unless the array[] values are set to zero, first!! ;)

Now go back through the array values you just calculated, and figure out the max. In pseudo code:

Code:

```int max = 0; for(each number in the array) {   multiply the value in the array, by i   if the result is > max       max = result }```
There are other ways to do this, but this is what I'd suggest.
• 09-04-2012
iMalc
In your last loop j goes up to 99, but you use that to index into the array called 'temp' which only contains 80 items. That's called a buffer overrun.
• 09-06-2012
20120903
Thank you for both of your suggestion.
Let's take 7 three's, 3 sixes, and 2 ten's to explain my code.
In the first loop, we can get temp[3]=21, temp[6]=18 and tmp[10]=10 as result.
In the second loop, we obtain maxValue = 21 and the answer should be 3.
I don't know why I can't get the correct result.
• 09-06-2012
AndiPersti
Quote:

Originally Posted by 20120903
I don't know why I can't get the correct result.

You don't initialise your temp array thus it contains random values from INT_MIN to INT_MAX (these are the lower and upper limits for an integer on your computer). It's very likely that any element has a higher value than 21 and that's why you get the wrong index.

You should change temp to
Code:

`int temp[100] = { 0 };`
so that every element is set to 0.

Bye, Andreas
• 09-06-2012
20120903
My code works now. Thank you.