Swap Function For Array

Hi, I need some help with swapping elements within the Array.

I already have the construct array code etc, so I am giving an example of what I am trying to do..

How do I swap an element in the array itself? Please help out, thank you.

void swapArray (int [], int, int&, int&);
{



}
you gave no names to your parameters so i have no point of reference here.
but, if you want to swap values between any variables, including elements in an array, you first need to make some space.

1
2
3
temp = value1;
value1 = value2;
value2 = value1;


equally with an array, its only the syntax that changes.
1
2
3
temp = ar[5];
ar[5] = ar[6];
ar[6] = temp;
Hi Jay, my bad.. Here is my code, can u guide me on how it should be done?


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 <ctime>
#include <cstdlib>
using namespace std;

const int MAX = 20;

void constructArray (int [], int);

void printArray (const int [], int);

void swapArray (int [], int, int&, int&);


int main ()
{
	int a [MAX];
	int largest, smallest;
	int size;
	
	srand (time (NULL));
	

	for (int i = 1; i <= 1; i++)
	{
		size = rand () % 11 + 10;
		
			
		cout << "Given the following array\n";
		cout << "  ";
		constructArray (a, size);
		printArray (a, size);
		cout << endl;
		
		
		
	}
}

void constructArray (int a [], int size)
{
	for (int i = 0; i < size; i++)
		a [i] = rand () % 51;
}

void printArray (const int a [], int size)
{

	for (int i = 1; i < size; i++)
		cout << a [i] << "  ";
	cout << endl;
}


void swapArray (int a[], int size, int& left, int& right)
{
 	

		
]

sure

1
2
3
4
5
6
void swapArray (int a[], int size, int& left, int& right)
{
    int temp = a[left];
    a[left] = a[right];
    a[right] = temp;
}


and to test it, add this into your for loop

1
2
3
4
5
int first=1, second=2;
swapArray(a,size,first,second);

printArray (a, size);
cout << endl;


you can run it here http://cpp.sh/63tsw

edit/
imagine you have 2 egg cups with eggs in them, and can only move one egg at a time. you HAVE to put one of the eggs to one side to free up its cup, then you can move the other egg, freeing up ITS cup for the egg you placed to one side.
Last edited on
Thanks a lot Jay, the explanation cleared my doubts.

I actually knew about storing in temp, but didn't I have to int temp :P Thanks again, have a nice day Jay!
Topic archived. No new replies allowed.