Swap Function

closed account (G60iz8AR)
Does anyone know how to write a swap function? if so please help

#include <iostream>
#include <string>
using namespace std;

// SWAP FUNCTION PROTOTYPE HERE


int main ()
{
int x,y;
cout << "Enter a two small positive numbers: ";
cin >> x >> y;
cout << "Before swap: x=" << x << " y= " << y << endl;
// swap( x , y );
cout << "After swap: x=" << x << " y= " << y << endl;

return 0;
}


// SWAP FUNCTION BELOW
1
2
3
temp = x;
x = y;
y = temp;
I have not done a ton of these is the past, mainly because my past is small but to swap you need a "third seat."

I.E how would you swap 2 liquids in glasses? Get a third glass.

so something like this might help.

void main()
{
int x = 1,y = 2, z = 0;

z = x;
x = y;
y = z;

cout that and x and y should now be swapped. There is also a swap function in visual studio 2012 if you are using that, but you'd have to google that ;P

Good luck, hope this helped


}

Eyenrique-MacBook-Pro:Desktop Eyenrique$ ./swap 
Enter two small inetegrs
Number 1: 2
Number 2: 7
Before swap pass by value function x=2 y=7
After swap pass by value function x=2 y=7


Before swap pass by reference function x=2 y=7
After swap pass by reference function x=7 y=2


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
//swap.cpp
//##

#include <iostream>
using std::cout;
using std::cin;
using std::endl;


void swap_pass_by_value_function(int number1,int number2);
void swap_pass_by_reference_function(int& number1,int& number2);

int main(){

int x,y;

cout<<"Enter two small inetegrs\n";
cout<<"Number 1: ";
cin>>x;
cout<<"Number 2: ";
cin>>y;

cout<<"Before swap pass by value function x="<<x<<" y="<<y<<endl;
swap_pass_by_value_function(x,y);
cout<<"After swap pass by value function x="<<x<<" y="<<y<<endl;
cout<<"\n\nBefore swap pass by reference function x="<<x<<" y="<<y<<endl;
swap_pass_by_reference_function(x,y);
cout<<"After swap pass by reference function x="<<x<<" y="<<y<<endl;


return 0; //indicates success
}//end main

void swap_pass_by_value_function(int number1,int number2){
        int temp;
        temp=number1;
        number1=number2;
        number2=temp;
}//end function swap_pass_by_value_function

void swap_pass_by_reference_function(int& number1,int& number2){
        int temp;
        temp=number1;
        number1=number2;
        number2=temp;
}//end function swap_pass_by_reference_function 
closed account (G60iz8AR)
@popup271 I used notepad ++ with the command prompt on windows will it work there ?
Topic archived. No new replies allowed.