find the highest element

How to find the highest element from random number?

Here is my code:

I have 30 random number and store in array and it be will pass to this function. I need to count occurs most frequently number in size of 30.
1
2
3
4
5
6
7
8
9
10
11
12
13
   //int count[size2];
    int max=0;
    
    for (int index = 0; index < size2; index ++)
    {
        if (max < mode[index])
        {
            max = mode[index];
            
            cout <<"This is the max " << max << " Position is " << mode[index]<< endl;
        }
    }
    


Output is
This is the max 19 Position is 19
This is the max 24 Position is 24
This is the max 27 Position is 27
This is the max 29 Position is 29
This is the max 30 Position is 30
This is the max 1513237040 Position is 1513237040
This is the max 1800426096 Position is 1800426096
Last edited on
1) The size2 is larger than the true size of the array.
By using invalid indexes you go out of bounds (outside the array) and get garbage values.

2) You want to print index and not mode[index] to see the position:

cout <<"This is the max " << max << " Position is " << index << endl;

Edit: maybe I made a mistake in 1) so if size2 is correct:

3) Be sure to fill in the entire array with values, or else possible garbage values will remain.

1
2
3
4
5
6
7
8
9
int a[4];

a[0] = 10;
a[1] = 20;

// a[0] == 10
// a[1] == 20
// a[2] == garbage value
// a[3] == garbage value 
Last edited on
catfish i dont understand: size2 is 30 random number.
. I need to count occurs most frequently number in size of 30.
if i put index didnt show up

I am so so confuse

1
2
3
4
5
6
7
8
9
10
11
12
  int max=0;
    
    for (int index = 0; index >size2; index ++)
    {
       // count[mode[index] - 1]++;
        if (mode[index] > max)
        {
            max = mode[index];
            
            cout <<"This is the max " << max << " Position is " << mode [index]<< endl;
        }
    }
@Chubby

Your for loop, is written incorrectly.

for (int index = 0; index >size2; index ++)

It should be..

for (int index = 0; index <size2; index ++)

You have it as >, and it should be <

i change it and it outter bound:
the output is
This is the max 20 Position is 20
This is the max 26 Position is 26
This is the max 52 Position is 52
This is the max 64 Position is 64
This is the max 78 Position is 78
This is the max 85 Position is 85
This is the max 88 Position is 88
This is the max 91 Position is 91
This is the max 94 Position is 94
This is the max 99 Position is 99
Topic archived. No new replies allowed.