Introduction
In this lab, we will learn how to swap two numbers using pointers in C++. The program swaps two numbers by passing their addresses to the function and uses pointers to point to their locations in memory.
In this lab, we will learn how to swap two numbers using pointers in C++. The program swaps two numbers by passing their addresses to the function and uses pointers to point to their locations in memory.
First, we include the necessary header files and declare the swap
function that takes two integer pointers as arguments.
#include <iostream>
using namespace std;
//Swap function to swap 2 numbers
void swap(int *num1, int *num2);
swap
functionHere, we implement the swap
function as follows:
void swap(int *num1, int *num2) {
int temp;
//Copy the value of num1 to some temp variable
temp = *num1;
//Copy the value of num2 to num1
*num1 = *num2;
//Copy the value of num1 stored in temp to num2
*num2 = temp;
}
The function takes in two integer pointers as arguments and swaps the values they point to using a temporary variable.
swap
functionDeclare num1
and num2
variables and use cin
to input their values. Call the swap
function and pass in their addresses as arguments.
int main() {
int num1, num2;
//Inputting 2 numbers from user
cout<<"Enter the first number : ";
cin>>num1;
cout<<"Enter the Second number : ";
cin>>num2;
//Passing the addresses of num1 and num2
swap(&num1, &num2);
Output the swapped numbers using cout
.
//Printing the swapped values of num1 and num2
cout<<"First number : "<< num1 << endl;
cout<<"Second number: "<<num2 << endl;
Save the program in the ~/project
directory as main.cpp
. Use the following command to compile the code
g++ main.cpp -o main && ./main
In this lab, we have learned how to swap two numbers using pointers in C++. We declared and defined a swap
function that swapped the values two integer pointers point to and used cin
and cout
to get user input and display output, respectively.