Jul 12, 2016 at 4:18pm UTC
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 Jul 12, 2016 at 4:24pm UTC
Jul 12, 2016 at 4:22pm UTC
Hi,
Firstly, why did you name your variable int aray[]
. That looks quite ugly and it is not even a correct English word.
Jul 12, 2016 at 4:24pm UTC
So where is your swap_array() function?
Jul 12, 2016 at 4:25pm UTC
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 Jul 12, 2016 at 4:26pm UTC
Jul 12, 2016 at 4:29pm UTC
To be able to swap an array, you need at least two arrays .
However, only one is mentioned.
Jul 12, 2016 at 4:35pm UTC
not trying to swap arrays trying to swap the order of the array
Jul 12, 2016 at 5:08pm UTC
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 =)
Jul 12, 2016 at 5:26pm UTC
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 Jul 12, 2016 at 5:26pm UTC