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
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