c++ swapping two numbers
To swap two numbers in C++, you can use a temporary variable to store the value of one of the numbers before exchanging them. Here are the steps to swap two numbers in C++:
Declare and initialize two variables, let's say
a
andb
, with the values you want to swap.Declare a temporary variable, let's say
temp
, to store the value ofa
temporarily.Assign the value of
b
toa
. This step replaces the value ofa
with the value ofb
.Assign the value of
temp
tob
. This step replaces the value ofb
with the original value ofa
that was stored intemp
.
After these steps, the values of a
and b
will be swapped.
Here is the code snippet that demonstrates the swapping of two numbers in C++:
int main() {
int a = 10;
int b = 20;
int temp;
temp = a;
a = b;
b = temp;
return 0;
}
In this example, we have two numbers, a
with a value of 10 and b
with a value of 20. By using a temporary variable temp
, the values of a
and b
are swapped, resulting in a
being 20 and b
being 10.