### Loop and array - variable not being set properly

Hello,

I am trying to make a simple program which will generate random numbers up to a predetermined limit and take count of how many times each number repeats itself during the number of times the code is run.
This part all works fine and dandy but my problem lies with getting the number that repeated the most times (line 32-35). I have a variable called maxnum which is supposed to be set if the times a number was generated is greater than it. This doesn't happen though. I get outputs like this:
 ``` 00 - 14 times, 01 - 12 times, 02 - 9 times, 03 - 14 times, 04 - 5 times, 05 - 6 times, 06 - 8 times, 07 - 10 times, 08 - 12 times, 09 - 10 times, The number that repeated the most is: 09 - 10 times ```

I have no idea why it always gets set to 9 when there are 3 numbers greater than it.

Any help would be greatly appreciated!
 ``12345678910111213141516171819202122232425262728293031323334353637383940`` ``````#include #include #include #include using namespace std; #define MAX_RNUM 10 #define MAX_TIMES 100 int main() { srand(time(NULL)); int i[MAX_RNUM], maxnum = 0; for (int j = 0; j < MAX_RNUM; j++) // set the entire array to 0 i[j] = 0; for (int j = 0; j < MAX_TIMES; j++) // filling the array with how many times each number up to MAX_RNUM repeated in MAX_TIMES { int r = rand()%MAX_RNUM; i[r]++; } for (int j = 0; j < MAX_RNUM; j++) { printf("%02d - %d times, \t", j, i[j]); // printing the entire array } for (int j = 0; j < MAX_RNUM; j++) { if (i[j] > maxnum) { maxnum = j; // if the number of times number 'j' has repeated is larger than maxnum, set maxnum to 'j' } } printf("\n\nThe number that repeated the most is: %02d - %d times", maxnum, i[maxnum]); // display the number that repeated the most return 0; } ``````

P.S.: I know this program will only set 1 number as the most repeated one if there are multiple - that is not a problem for now.
Last edited on
Line 32
 `` `` `` if (i[j] > maxnum)``
should be:
 `` `` `` if (i[j] > i[maxnum])``
Oh crap, I've been looking the code for over 2 hours now and I haven't realised that's the mistake!

Thanks a bunch man!
Topic archived. No new replies allowed.