C++ program to swap two numbers using pointers

C++ program to swap two numbers using pointers

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int *a,*b,*temp;
cout<<“Enter value of a and b:”;
cin>>*a>>*b;

temp=a;
a=b;
b=temp;

cout<<“nAfter swapingna=”<<*a<<“nb=”<<*b;
getch();
}

One thought on “C++ program to swap two numbers using pointers

  1. David Thiessen

    Here is how I rewrote:

    //this program will swap two ints using ptrs

    #include

    using namespace std;

    int main()
    {
    int* a = new int;
    int* b = new int;

    cout << "Enter value of a and b:";
    cin >> *a >> *b;

    //put a in temp
    int* temp = a;
    //put b in a
    a = b;
    //put temp, was a, into b
    b = temp;

    cout << "nAfter swapingna=" << *a << "nb=" << *b;

    delete a;
    delete b;

    return 0;
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *