Swap Two Numbers using Pointers in C, C++

Leave a Comment
Write a C, C++ program to swap two numbers using pointers. So swapping two numbers using pointers means we are using call by reference method.

Swap two numbers without using third variable .

Swap two numbers using third variable .

Call by Reference

1. In call by reference method actual parameter is modified. Because a pointer to the data is copied. So Changes to the data pointed by the pointer are reflected in the data of the calling function.

2. To pass an argument using call by reference we use the address operator(&).

3. Using call by reference no additional memory is used as we are using pointers.

C, C++ Interview Questions .

Swap Two Numbers using Pointers in C


void swapValue(int *a,int *b);

int main(){

   int a = 100;
   int b= 200;

   printf("First number is %d",a);
   printf("Second Number is %d",b);


   printf("After swap function \n");


void swapValue(int *x,int *y){

      int temp;
      temp = *x; 

Swap Two Numbers using Pointers in C++

#include <iostream>
using namespace std;

void swapvalue (int *a, int *b) {
 int temp;
 temp = *a;
 *a = *b;
 *b = temp;

int main() {

 int a, b;
 cout << "Enter two numbers: \n";
 cin >> a >> b;
 /* Passing address .*/
        swapvalue(&a, &b);
 cout << "After swapping first and second number is "<<a <<" "<<b;
 return 0;

Output :

Enter two numbers : 6       7

After swapping first and second number is 7  6
If You Enjoyed This, Take 5 Seconds To Share It


Post a Comment