Integer Swapping

hk3008

Distinguished
Jan 29, 2012
43
0
18,580
ok so I have

#include <iostream>
#include <cmath>
#include <stdio.h>

using namespace std;

void swap ( int &x, int &y);


int main()

{
int number;
cout << "x is ";
cin >> number;
int x = number;

cout << "y is ";
cin >> number;
int y = number;

swap( x, y);
cout << "Swapped the first number is now(" << x << ")and the second is now (" << y << ")";

return 0;
}

and i am just trying to get it to swap them with no avail any and all help would be greatly appreciated
 

randomizer

Distinguished
Before you write any code, think about your design and what you are trying to accomplish. This exercise is easy to do only if you understand what happens when you do a variable assignment. Get out the pen and paper, draw some boxes representing X and Y with their values inside and try to work out how you're going to get them to swap without losing either value.

Alternatively, you could probably Google for a simplistic swap implementation, but there's no point writing a function that you don't understand. If you don't understand variable assignments (a fundamental concept) then you'll never progress past the most basic programming.
 

hk3008

Distinguished
Jan 29, 2012
43
0
18,580
you are right if I dont understand then I wont really know but just learning the basics for me has been easier by seeing examples I have been reading forum after forum looking for info on what type of form to use for certain issues but even then it is hard to understand but some one was even saying to use temp values but that is for user input but ok after many hours of research this is what I have found out

#include <iostream>
using std::cout;

void swap(int& i, int& j)
{
int t = i;
i = j;
j = t;
}

int main() {
int a = 1, b = 2;
cout << "Before. a: " << a << ", b: " << b << "\n";
swap(a, b);
cout << "After. a: " << a << ", b: " << b << "\n";

system("pause");
}

It works and even pauses and shows results but however I want to be able to have a user input for the numbers how would I go about this?
 

theDanijel

Distinguished
May 4, 2011
74
0
18,590



This is a very important question, because if you don't understand that, then you are just not cut out to be a programmer. In every school and programming class if you don't know the awnser to this, you should automaticaly fail that class.
 

hk3008

Distinguished
Jan 29, 2012
43
0
18,580
I need the 3rd or temp variable because the two variables cannot be the same number or it will not work so I assign x to one then y to 2 then I have to sign x or y to 3 and switch the integers