Fixing assignment errors

trying to output the random INTs in an array from smallest to largest. output that actually comes out is usually the smallest int then the largest, repeating.

this is an assignment so help instead of direct answers would be appreciated.


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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
  #include <iostream>	//
#include <time.h>	//
#include <string>	//
using namespace std;

int main()
{
	int nums[5];
 	int BigNum = 0;
	int NextNum = 0; 
	int MidNum = 0;
	int SecNum = 0;
	int SmallNum = 0;
	string Again;

	srand(time(NULL));
	do
	{
		for(int j = 0; j < 5; j++)
		{
			nums[j] = rand()%100;
		}

		for (int i = 0; i <5; i++)
		{
			cout<< nums[i]<<endl;
		}

		BigNum = nums[0];

		for (int k = 1; k<5; k++)
		{
			if(nums[k] < BigNum)
			{
				BigNum = nums[k];
			}
		}

		NextNum = nums[0];

		for (int r = 1; r<5; r++)
		{
			if(nums[r] < BigNum)
			{
				NextNum = nums[r];
			}
		}

		MidNum = nums[0];

		for (int g = 1; g<5; g++)
		{
			if(nums[g] < NextNum)
			{
				MidNum = nums[g];
			}
		}

		SecNum = nums[0];

		for (int b = 1; b<5; b++)
		{
			if(nums[b] < MidNum)
			{
				SecNum = nums[b];
			}
		}

		SmallNum = nums[0];

		for (int c = 1; c<5; c++)
		{
			if(nums[c] < SecNum)
			{
				SmallNum = nums[c];
			}
		}

		cout<<"\nsmallest to largest:"<<endl<<SmallNum<<endl<<SecNum<<endl<<MidNum<<endl<<NextNum<<endl<<BigNum<<endl;

		cout<<"\n\nWould you like to run again? ('y' or 'n') ";
		cin>>Again;
	} while (Again != "n");

	return 0;
}
sort the array, then write it out in a loop.
Personally I like to use shell sort, which is simple to code and quite good at its job. You should be able to find pseudo code for this (or if you insist, bubblesort, which is like 2 lines of code shorter and a billion times slower) on the web.


while you can do it your way, it impractical for more than 3 items; as you can see even 5 is painful.
Last edited on
Topic archived. No new replies allowed.