Random numbers, Display the highest, second highest, and the lowest number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
	const int num = 10;
	int ran[num], high =0, high2, low = 16;
	srand(time(NULL));      //code to generate random numbers

	for (int i = 0;i < num;i++)
	{
		ran[i] = rand()%15+1;  //the maximum number that will be generated is 15
	}

	
	for (int i = 0; i < num;i++)
	{
		cout<<ran[i]<<' ';

	}

	for (int count=0; count < num; count++ )
	{
		
		if (ran[count] > high)
		{
			high2 = high;
			high = ran [count];
		}
		
		
		else if (ran[count] > high2)
		    high2 = ran[count];

		
		if (ran[count] < low)
		{
			low = ran[count];
		}

	}


	
	    cout<<endl;
		cout<<"The highest number is "<<high<<endl;
		cout<<"The second highest number is "<<high2<<endl;
		cout<<"The lowest number is "<<low<<endl;

	system ("pause > 0");
		return 0;
}



the second highest number displays the duplicate of the highest if ever there is one.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int ran[num], high, high2, low;

//... this code is skipped
 
high = high2 = low = ran[0];
 
for ( int count=0; count < num; count++ )
{
   if ( high < ran[count] )
   {
      high2 = high;
      high = ran [count];
   }
   else if ( high2 < ran[count] )
   {
      high2 = ran[count];
   }
   else if ( ran[count] < low )
   {
      low = ran[count];
   }
}
it still displays the duplicate.

ex set.
15 12 15 13 8 6 4 5 9 10

it displays

The highest number is 15
The second highest number is 15
The lowest number is 4

it should be like this:
The highest number is 15
The second highest number is 13
Last edited on
Topic archived. No new replies allowed.