Help with arrays!!


Im working on this program where i need to automatically generate 10 random numbers using an array, but the user will decide the range of the random numbers by choosing a min and max value.
Then I need to sort the array, find the median and the user needs to call upon a arrau location for the value (user can choose to see the value of array 4)

Below is my code,
the program runs without errors but it's not functioning properly.

Problems;
1) I set up my array to show me printout the random numbers after its been sorted, array[2] is way off. Everytme if run the code its always that location that has some crazy negative number.

2) My median formula is not working, i set it up so i sums up array[4] and [5] then divide it by two, thus getting the median.

3) i don't know how to set it up so the user can call a location for the value.

All help is appreciated.
Thanks

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
#include <iostream>
#include <cmath>
#include <ctime>

using namespace std;

int main()
{
	int max, min, swaphold(0), i; 
	int number[9], end(10), sort;
	double median;
	srand(time(0));
	
	  cout << "Enter lower limit \n";
	  cin >> min; 

	  cout << "Enter upper limit \n";
	  cin >> max;

	for (int i=0; i<10; i++)
	{
		
		number[i] = (rand()%(max-min))+ min;
	}
		
		
	for (int sort=9; sort>0; sort--)
	{	for (int i=0; i<end; i++)
		{
			if (number[i] > number[i + 1])
			{
			swaphold = number[i + 1];
			number[i+1]= number[i];
			number[i] = swaphold;
			} 
		} end--;
	}
	for (int i=0; i<10; i++)
	{
	cout << number[i] << ",  ";
	}

	median = (number[4]+number[5])%2;
	cout << median;

	return 0;
}


1) Use standard std::sort function:
1
2
3
4
5
#include <algorithm>

//...
std::sort(number, number + end); //Note that there isn't subscript operator ([]) here. We are passing pointers here.
//... 

2) you are using modulus operator, not division. Correct:
 
median = (number[4]+number[5]) / 2.0; //Note 2.0 here. It is here because C++ will use integer division if we leave just 2 here. 

3) Please elaborate what do you want
Thanks.

For the third part,
The program will create an array of 10 random numbers.
1-10 of different values.

The user can then call for what value array[4] is,
Lets say its 12.
Then user can call to find out what value array[7] is. And so
on.

I think it's using a search function.
1
2
3
4
5
6
7
8
std::cout << "enter array index, or 0 to exit: "
int input;
std::cin >> input;
while( 0 < input && input <= 10 ) {
    std::cout << "value = " << number[input - 1] << std::endl;
    std::cout << "enter array index, or 0 to exit: "
    std::cin >> input;
}
Thanks for the help.
Got it to work.

Topic archived. No new replies allowed.