Need help!

I need to create an array with 100 random numbers and then sort them in descending order. This is what I have so far (I'm pretty sure the problem is to do with the return values of the functions, but I don't know what else to do):
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 <stdlib.h>
#include <time.h>

using namespace std;

double* create_array(double*)
{
    double array[100];
    int t, size=100;

    for(t=0; t<size; t++) array[t]= rand()%250;

    return array;
}

double* sort_array(double* )
{
    double nums[100];
    int size=100;
    int a, b, t;
    for (a=1; a<size; a++)
        {
            for(b=size-1; b>=a; b--)
                {
                    if(nums[b-1] > nums[b])
                        {
                            t = nums[b-1];
                            nums[b-1] = nums[b];
                            nums[b] = t;
                        }
                }
        }
    return nums;
}

int main()
{
    srand(time(0));
    double num[100];
    int t, size=100;

    create_array(num);

    sort_array(num); // Call function to sort array //

    for(t=0; t<size; t++) cout<< num[t] <<" ";
    cout<<"\n";
    return 0;
}
At lines 7-9, array needs to be an argument, not a local variable.
1
2
double* create_array(double * array)
{  int t, size=100;


Line 14, you return array, but there is no need since it's passed as an argument. i.e. create_array can be a void function.

Lines 17-19, same problem. nums needs to be the argument.
1
2
double* sort_array(double * nums)
{   int size=100;


Line 34, no need to return nums since it is passed as an argument. i.e. sort_array can be a void function.




The assignment specified that the sort function be a double* type, unfortunately.
This is because your functions do not use their arguments but instead create them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double* create_array(double* array))
{
    double array[100];

    // ...

    return array;
}

double* sort_array(double* nums)
{
    double nums[100];

    // ...

    return nums;
}

I also couldn't get return(); to work, - in either subrt'n.

I did switch
int t; to
double t;
in the sort_array fnc()
because nums[] is filled with doubles,
and is being populated with 't''s,
therefore 't' should be a double.
- -
too, while this can still be tightened ( a lot)
I used this in MAIN() to show the output more clearly:

1
2
3
4
5
6
7

    for(t=0; t<size; t++) 
         printf("\n\n Element:  %d \t Value: %2d " , t, int (num[t])  );
	
	 getchar();   //<iostream>
    return 0;


Last edited on
Topic archived. No new replies allowed.