Swapping

#include <iostream>
using namespace std;
int main (void)
{
int x;
int y;
int temp;
cout << " input x: ";
cin >> x;

cout << "input y: ";
cin >> y;
temp =x;
temp =y;
y=x;
cout << "x= "<< x;
cout << "y= "<< y;
cout <<x;
cout << y;
return 0;
};

Could anyone help figure out why this doesn't work? I get the wrong values in the output.
1
2
temp =x;
temp =y;

You immediately overwrite temp. And you never use temp to write back to X

1
2
3
temp = x;
x = y;
y = temp;
Instead of

temp =x;
temp =y;
y=x;

write

temp = x;
x = y;
y = temp;

These two statements

cout <<x;
cout << y;

can be removed.
#include <iostream>
using namespace std;
int main (void)
{
int x;
int y;
int temp;
cout << " input x: ";
cin >> x;

cout << "input y: ";
cin >> y;
temp =x;
x=y;
y=temp;
cout << "x= "<< x;
cout << "y= "<< y;
return 0;
}


i did as you suggested, but i am still getting an error. Are there any basic rules for swapping?
I do not see any error in the code. Could you report what errors do you have?
The program does not produce the correct output. For example:
input x: 5
input y: 7
x= 7 y=

It is leaving the variable y blank, when I need it to say that y=5.
The program is correct and outputs the correct result.
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
#include <iostream>

int main (void)
{
	int x; // define variables
	int y;
	int temp;
	
	std::cout << "Input X value:  ";    // get x and y values form user
	std::cin >> x;
	std::cin.ignore();
	std::cout << "Input Y Value:  ";
	std::cin >> y;
	std::cin.ignore();
	
	temp = x;                            // switch values
	x = y;
	y = temp;
	
	std::cout << std::endl << std::endl;            // print new values
	std::cout << "Haha! I switched up your values!" << std::endl << std::endl;
	std::cout << "The new X = " << x << "." << std::endl;
	std::cout << "The new Y = " << y << "." << std::endl << std::endl;
	
	std::cout << "Press \'Enter\' to continue...";    //exit program safely
	std::cin.ignore();
	
return 0;
}
Last edited on
Try cout << endl; after the last cout statement. That should flush the contents of the output buffer and cause the full text to be displayed.
Topic archived. No new replies allowed.