Swap two numbers using pointers
Track completion, mastery, and revision.
C++ Program to Swap Two Numbers Using Pointers
Understanding Pointers in C++
Pointers are powerful C++ data types that store memory addresses rather than direct values. They provide direct access to memory locations, enabling efficient data manipulation and memory management. Read More.
Pointer Syntax
<data_type> *pointer_name;
The asterisk (*) operator is used to:
-
Declare a pointer variable
-
Dereference a pointer (access the value at the stored address)
Example Usage
int *ptr; // Pointer declaration
int value = 12;
ptr = &value; // Assign address of value to pointer
cout << ptr; // Output: Memory address of value
cout << *ptr; // Output: 12 (dereferenced value)
Pointer-Based Number Swapping Algorithm
Approach
The program demonstrates how to swap two numbers using pointers by:
1. Storing values in variables
2. Creating pointers to their memory addresses
3. Using a temporary pointer for the swap operation
4. Manipulating values through dereferenced pointers
Step-by-Step Algorithm
1. Prompt user for two integer inputs
2. Declare three pointers: two for the numbers, one temporary
3. Assign addresses of input variables to pointers
4. Perform swap using dereferenced pointers
5. Display results after swapping
Complete C++ Implementation
#include <iostream>
using namespace std;
int main() {
int a, b;
// Get user input
cout << "Enter two numbers separated by space: ";
cin >> a >> b;
// Display original values
cout << "\nOriginal values:";
cout << "\nFirst number = " << a;
cout << "\nSecond number = " << b;
// Pointer declaration and initialization
int *ptr1 = &a, *ptr2 = &b;
int temp;
// Swap values using pointers
temp = *ptr1; // Store value of a in temp
*ptr1 = *ptr2; // Assign value of b to a
*ptr2 = temp; // Assign original value of a (from temp) to b
// Display swapped values
cout << "\n\nValues after swapping:";
cout << "\nFirst number = " << a;
cout << "\nSecond number = " << b;
cout << "\n\nMemory addresses:";
cout << "\nAddress of first number: " << ptr1;
cout << "\nAddress of second number: " << ptr2;
return 0;
}
Sample Output
Enter two numbers separated by space: 14 16
Original values:
First number = 14
Second number = 16
Values after swapping:
First number = 16
Second number = 14
Memory addresses:
Address of first number: 0x7ffd5a2b5a68
Address of second number: 0x7ffd5a2b5a6c
Best Practices
-
Always initialize pointers (use
nullptrin modern C++) -
Check for null pointers before dereferencing
-
Avoid dangling pointers (pointers to freed memory)
-
Prefer references over pointers when possible for safer code
-
Use smart pointers (
unique_ptr,shared_ptr) for automatic memory management
Finished reading?