Program to swap two numbers using pointers

1 year ago Admin 0

Swap two numbers using pointers

This article illustrates the concept how to swap two numbers using pointers in c/c++.

swap two numbers using pointers

Here is the source code and output of both the programs.

C Programming language

Program


#include<stdio.h>
#include<conio.h>
void main()
{
 int num1,num2,*x,*y,temp;
 clrscr();
 printf("Enter value of a:- ");
 scanf("%d",&num1);
 printf("Enter value of b:- ");
 scanf("%d",&num2);
 x = &num1;
 y = &num2;
 printf("\nValue of a before swaping:- %d",*x);
 printf("\nValue of b before swaping:- %d",*y);

 temp = *x;
 *x = *y;
 *y = temp;
 printf("\nValue of a after swaping:- %d",*x);
 printf("\nValue of b after swaping:- %d",*y);
 getch();
}

After successfully compiling and executing the above C program,output is:-

swap two numbers using pointers


C++ Programming language

Program


#include
#include
void main()
{
 clrscr();
 int num1,num2,*x,*y,temp;
 cout<<"Enter value of a:- ";
 cin>>num1;
 cout<<"Enter value of b:- ";
 cin>>num2;
 x = &num1;
 y = &num2;
 cout<<"\nValue of a before swaping:- "<<*x;
 cout<<"\nValue of b before swaping:- "<<*y;

 temp = *x;
 *x = *y;
 *y = temp;
 cout<<"\nValue of a after swaping:- "<<*x;
 cout<<"\nValue of b after swaping:- "<<*y;
 getch();
}

After successfully compiling and executing the above C++ program,output is:-

swap two numbers using pointers


Comment below if you are facing any problem or you find any error in the above program and also subscribe to our newsletter for more updates.


Read more c/c++ Programs published by snapcout:-

Program to add two numbers using pointers
Program to reverse an entered array
Program to check if a given matrix is an identity matrix
Program to convert centimeters into meter and kilometer
Program to sort an array using insertion sort


About article

Written By:- Admin

Published on:- 21/08/2018

Published By:- Snapcout


Don't forget to share the article if you like it:-