C C++ program to swap values of two variable using pointer

Coding in C

#include<stdio.h>
int main()
{
    int n1,n2,*p1,*p2,temp;
    printf("Enter number1: ");
    scanf("%d",&n1);
    printf("Enter number2: ");
    scanf("%d",&n2);
    p1=&n1;
    p2=&n2;
    temp=*p1;
    *p1=*p2;
    *p2=temp;
    printf("Number1 = %d\n",n1);
    printf("Number2 = %d\n",n2);
    return 0;
}

Coding in C++

#include<iostream>
using namespace std;
int main()
{
    int n1,n2,*p1,*p2,temp;
    cout<<"Enter number1: ";
    cin>>n1;
    cout<<"Enter number2: ";
    cin>>n2;
    p1=&n1;
    p2=&n2;
    temp=*p1;
    *p1=*p2;
    *p2=temp;
    cout<<"Number1 = "<<n1<<endl;
    cout<<"Number2 = "<<n2<<endl;
    return 0;
}

Output

C C++ program to swap values of two variable using pointer

Published by

admin

I am a computer teacher, programmer and web developer