GigaCoders

Learn. Share. Code

Full width home advertisement

CPP Basics Live Series

Using the Qt Creator

Post Page Advertisement [Top]

 



Swapping two variables in C++ or any programming language is very easy. There are two ways this can done. First, is by using an additional variable to save the value of one of the variables to be swapped. The second is simply by using a little math.


The First Method - Using an additional Variable

int a = 3; //the first variable to be swapped

int b = 5; //the second variable to be swapped

int c = 0; //the extra variable to hold a value


c = a; //saving the value of the first variable to be swapped

a = b; //swap the first variable.

b = c; //you cannot do b=a because a has already been changed to the value of b. Therefore the extra                 variable that holds the value of a is needed.


The Second Method - Doing a little Math

int a = 3; //the first variable to be swapped

int b = 5; //the second variable to be swapped


a = a + b; // a = 3 + 5 = 8
b = a - b; // b = 8 - 5 = 3; b is now 3
a = a - b; // a = 8 - 3 = 5; a is now 5


Personally, this method is much more tedious to remember. Also, in the future when you will start working with object-oriented programming and using user-defined data types, it is better to use the first method.


Creating a program in C++ to swap two variables




Resources About Data Types

https://www.w3schools.com/cpp/cpp_data_types.asp

https://www.tutorialspoint.com/cplusplus/cpp_variable_types.htm













No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib