Array task - rand() issue

Hello everyone!

In this topic I would like to recieve some help from you guys with my arrays task. Namley I was asked to create two arrays, A and B with the same size of an array (100). Then I had to arrange these 100 values in the array, which I generated with rand() operate, in an ascending order for A[i] and descending order for B[i]. Unfortunetly my program doesn't work as although it returns the indexes (i=1,i=2,...,i=100 & i=100,i=99,...,i=1) it deosn't seem to put the generated random values in order. Could somebody please help?

Thanks so much!

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
 #include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    const int array_size=100; // size for A,B & C
    double A[array_size];
    double B[array_size];

    for(int i=0; i<array_size; i++)
    {
        A[i]=rand()%100+1;
    }

     for(int i=0; i<=array_size; i++)
    {
        cout<<"i:"<<i<<" array A: "<<A[i]<<endl;
    }

    for(int i=0; i<array_size; i++)
    {
        for(int j=i+1; j<array_size; j++)
        {
           if(A[i]>A[j])
            {
           double swaper1;
            A[i]= swaper1;
            A[j]= A[i];
            swaper1=A[j];
            }
        }
    }

    cout<<endl;


     for(int i=array_size; i>+0; i--)
    {
        B[i]=rand()%100+1;
    }

    for(int i=array_size; i>=0; i--)
    {
        cout<<"i:"<<i<<" array B: "<<B[i]<<endl;
    }

    for(int i=array_size; i>=0; i--)
    {
        for(int k=array_size; k>=0-1; k--)
        {
             if(B[i]>B[k])
            {
                double swaper2;
                swaper2=B[i];
                B[k]= B[i];
                B[k]= swaper2;
            }

        }
    }
closed account (E0p9LyTq)
Are you required to write the code to sort the arrays? There are two C++11 function templates in <algorithm> that will do the work for you.

std::sort and std::reverse.
Neither swapping sequence is correct.

On line 28 you declare a variable swaper (with nothing meaningful in) and then on line 29 you set your A[i] to that non-meaningful value. The next two lines are also setting wrong variables.

On lines 57 you set the same variable twice, but you never set B[i].

Swapping is a classic three-line sequence in c++. Work it out with any numbers you like on paper.
Topic archived. No new replies allowed.