Write the code for swapping two numbers using * and / operators
In this step, we will write the code for swapping two numbers using * and / operators. The code should take two numbers from the user and swap them without using a third variable.
// swap.cpp
#include <iostream>
using namespace std;
void swap_numbers(int &x, int &y) {
x = x * y;
y = x / y;
x = x / y;
}
int main() {
int a, b;
cout << "Enter the value of a: ";
cin >> a;
cout << "Enter the value of b: ";
cin >> b;
cout << "Before swapping: " << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap_numbers(a, b);
cout << "After swapping: " << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}
In this code too, we have created a function swap_numbers
which takes two integer arguments and performs the swapping operation. We take two numbers a
and b
from the user and call the function swap_numbers
which swaps their values. Finally, we print the swapped values of a
and b
. In this method of swapping, we use multiplication and division operations instead of addition and subtraction.
To run the program, use the command:
g++ swap.cpp -o swap && ./swap