🔁 Swapping Two Numbers Using Pointer Arithmetic in C++
Swapping two numbers using pointer arithmetic is a foundational concept in C++ that helps you understand how memory and variables interact at a low level. It’s commonly used in embedded systems, algorithms, and interview questions.
📘 What is Pointer Arithmetic?
Pointer arithmetic refers to performing operations on pointer variables, such as incrementing addresses or dereferencing memory. By using it, we can access and manipulate the actual memory where values are stored.
📄 C++ Code Example
#include <iostream>
using namespace std;
void swapPointer(int* a, int* b) {
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
int main() {
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "\nBefore Swapping:\n";
cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
swapPointer(&num1, &num2);
cout << "\nAfter Swapping:\n";
cout << "num1 = " << num1 << ", num2 = " << num2 << endl;
return 0;
}
📝 Sample Output
Enter first number: 20 Enter second number: 45 Before Swapping: num1 = 20, num2 = 45 After Swapping: num1 = 45, num2 = 20
💡 Explanation
- *a = *a + *b; — Adds the values and stores the total in
*a
- *b = *a - *b; — Derives original
*a
value into*b
- *a = *a - *b; — Calculates the original
*b
value into*a
This technique avoids the use of a temporary variable and demonstrates in-place memory manipulation. Perfect for memory-efficient applications and understanding low-level programming!
Post a Comment