C++ swap() by passing pointers Write a swap() function that only takes pointers
ID: 3776375 • Letter: C
Question
C++
swap() by passing pointers
Write a swap() function that only takes pointers to two integer variables as parameters and swaps the contents in those variables using the above pointers and without creating any extra variables or pointers. The swapped values are displayed from the main(). Demonstrate the function in a C++ program.
Tip: Before using pointers, it will be a good idea to figure out the logic to swap two variables without need of any extra variables. Then, use pointer representations in that logic.
Enter n1 n2: 10 7
After swapping, n1=7 and n2=10
Explanation / Answer
Here is the C++ code below:
#include <iostream>
void swap(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
int main()
{
int n1 = 0;
int n2 = 0;
std::cout << "Please enter n1: ";
std::cin >> n1;
std::cout << "and n2: ";
std::cin >> n2;
swap(&n1, &n2);
std::cout << " After swapping, n1 = " << n1 << " and n2 = "<< n2 <<" ";
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.