order swapping array

hi people I know how to swap two indexes in an array lets say the first and second but I'm not sure how I would swap them all I don't mind which order,how would I go about doing this a for loop? a while loop? any ideas on how I would get this to work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>

using namespace std;


void swap(int aray[],int firstIndex,int secondIndex){

      int temp = aray[firstIndex];
      aray[firstIndex] = aray[secondIndex];
      aray[secondIndex] = temp;

}

int main()
{

   int ray[5];
   for(int i = 0;i < 5;i++){

       cout << "enter values" << endl;
       cin >> ray[i];
   }
}
Last edited on
Hi,
Firstly, why did you name your variable int aray[]. That looks quite ugly and it is not even a correct English word.
So where is your swap_array() function?
Ok so heres the solution I came up with but the order seems pretty random if I input 1,2,3,4,5 I get
2
5
1
3
4
as the output but how would I go about reversing the order of the numbers entered in the array?

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

#include <iostream>

using namespace std;


void swap(int aray[],int firstIndex,int secondIndex){

      int temp = aray[firstIndex];
      aray[firstIndex] = aray[secondIndex];
      aray[secondIndex] = temp;

}

int main()
{

   int ray[5];
   for(int i = 0;i < 5;i++){

       cout << "enter values" << endl;
       cin >> ray[i];
   }

   cout << " -------- " << endl;



   for(int i = 0; i < 5;i++){

      int j = 1;
      swap(ray,i,j);
      j++;

   }


   for(int i = 0;i <5;i++){

      cout << ray[i] << endl;

   }
}


Last edited on
To be able to swap an array, you need at least two arrays.

However, only one is mentioned.
not trying to swap arrays trying to swap the order of the array
> How would I go about reversing the order of the numbers entered in the array?

1
2
3
4
5
6
7
int t, n = (sizeof(ray) / sizeof(int));
for(int i = 0;i < n / 2; i++)
{
    t = ray[i]; 
    ray[i] = ray[n-i-1]
    ray[n-i-1] = t;
}
I'm not sure how I would swap them

Your swap routine is correct. However, you haven't made clear WHY you want to swap any entries. That determines how you would call swap.

The usual reason for swapping items is to sort an array into order, but as I said, you have not indicated your intent.
thanks for the help man much appreciated =)

but just a question could you explain the code a little I'm kind of confused to how it actually works haha =)
hi Anon I'm looking to try swap them in reverse or in other words just reverse the order of the array
Last edited on
Glad it helped :)
Topic archived. No new replies allowed.