ask a question and answer it in code c++
Question: How can you swap the values of two variables in C++?
#include <iostream>
int main() {
// Declare and initialize two variables
int a = 5;
int b = 10;
// Print the original values
std::cout << "Before swapping: a = " << a << ", b = " << b << std::endl;
// Swap the values using a temporary variable
int temp = a;
a = b;
b = temp;
// Print the swapped values
std::cout << "After swapping: a = " << a << ", b = " << b << std::endl;
return 0;
}
Explanation:
1. Declare and initialize two integer variables, a
and b
, with initial values of 5 and 10, respectively.
2. Print the original values of a
and b
using std::cout
.
3. Declare an integer variable temp
to temporarily store the value of a
.
4. Swap the values of a
and b
by assigning the value of b
to a
and the value of temp
to b
.
5. Print the values of a
and b
after the swap using std::cout
.
6. The program returns 0, indicating successful execution.