VB icon

Swap Magic

Email
Submitted on: 1/3/2015 8:37:00 PM
By: FAzle AreFin (from psc cd)  
Level: Beginner
User Rating: By 7 Users
Compatibility: C, C++ (general), Microsoft Visual C++, Borland C++, UNIX C++
Views: 332
 
     Do you think it is possible to swap values between two variables without using a third temporary variable? What? No? Yes? Well, the answer is...YES. Take a look at the code and don't forget to vote!
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
				
//**************************************
// Name: Swap Magic
// Description:Do you think it is possible to swap values between two variables without using a third temporary variable? What? No? Yes? Well, the answer is...YES. Take a look at the code and don't forget to vote!
// By: FAzle AreFin (from psc cd)
//**************************************

/*	
	Swapper
	Swaps values between two variables without using a third temporary variable
	Programmer: Fazle Arefin
*/
/*	
	use #include <iostream.h> and cout instead of #include <stdio.h> and printf
	if you are using C++, this gives type safety, I didn't use them to keep this
	program C compatible
*/
#include <stdio.h>
int main() {
	int a = 10;
	int b = 20;
	printf("Before swapping a = %d and b = %d \n", a, b);
	a = a + b;
	b = a - b;
	a= a - b;
	/*	
		instead of + and - you can use * and / respectively
		a = a * b;
		b = a / b;
		a= a / b;
		
		instead of + and - or * and / you can use the XOR operator ^
		but this restricts you to only swapping integers
		a = a ^ b;
		b = a ^ b;
		a= a ^ b;
	*/
	
	printf("After swapping a = %d and b = %d \n", a, b);
	return 0;
}


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.