How to Swap Two Integers Using Pointers

This Program swap two numbers using pointers in C++ . Pointers contain the memory address of the variable and also used to allocate the dynamic memory in the program. In this problem there are two pointers and swap their values with simple logic.

Source Code

#include<iostream>
using namespace std;
int main ()
{
 int a, b, *p1,*p2;
 cout<<"\t \t \t LEP Tutorials \n \n \n ";
 cout<<" Enter Your First Number : ";
 cin>>a;
 cout<<"  Enter Your Second Number: ";
 cin>>b;
 p1 = &a;
 p2 = &b;
 a = *p1 + *p2;
 b = *p1 - *p2;
 a = *p1 - *p2;
 cout<<"  Number After Swapping   : "<< a <<endl;
 cout<<"  Number After Swapping   : "<< b <<endl;
}

Output of the Program

Pointer to Swap Two Integers

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment