Click here to Skip to main content
15,904,877 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
i dont know what is wrong with this code ......values of x and y are something out of this world .....

What I have tried:

using namespace std;

int main()

{
int x,y,z,t;
cout<<"x=";
cin>>x;
cout<<"Y=";
cin>>y;
x=z;
y=t;
cout<<"after swaping";
cout<<"value of y"<<z<<endl;
cout<<"value of x"<<t<<endl;



return 0;}
Posted
Updated 20-Dec-16 9:44am
Comments
Michael_Davies 20-Dec-16 10:36am    
Your not swapping anything, z & t are not initialised and you are overwriting the inputs in x & y with them.

Your also saying "value of x" then outputting t which is not initialised.

Initialise z & t to 1234 and 4321 and see what happens.

You set x to z but z is never initialised so will just have some random value, same with t (which you don't need anyway).


The correct logic would be z = x, x = y, y = z.
 
Share this answer
 
Comments
Member 12914219 20-Dec-16 11:23am    
are x=z and z=x differnt?
PeejayAdams 20-Dec-16 11:34am    
Yes. Assignment goes to the left, so x = z would give x the value of z whereas z = x would give the value of x to z.

If we were assigning a value from a value rather than a variable we'd say, for example, "x = 2;" which effectively reads as "Let x have the value of 2." Similarly, when we say "x = z;" we are saying "Let x have the value currently assigned to z."
Um...You need to learn to use the debugger...
C++
int x,y,z,t;
Declares four variables, but does not give them any "sensible" value.
C++
cout<<"x=";
cin>>x;
cout<<"Y=";
cin>>y;
Reads a value into x and y
C++
x=z;
y=t;
Overwrites the values you read from the user with uninitialized values which contain no useful data.
That isn't a swap.
To swap, you don't need z, just t:
C++
t = x;
x = y;
y = t;
 
Share this answer
 
This is reversed,
C++
x=z;
y=t;

and should be replaced with
C++
z=x;
t=y;

but even with this correction, it is not a swap.

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900