Here, we have a basic program example to swap two element using pointer in C and C++.
Code to swap numbers using element in C language
#include <stdio.h>
void swapNumbers(int *x,int *y,int *z);
int main()
{
int num1,num2,num3;
printf(" Input the value of 1st element : ");
scanf("%d",&num1);
printf(" Input the value of 2nd element : ");
scanf("%d",&num2);
printf(" Input the value of 3rd element : ");
scanf("%d",&num3);
printf("\n The value before swapping are :\n");
printf(" element 1 = %d\n element 2 = %d\n element 3 = %d\n",num1,num2,num3);
swapNumbers(&num1,&num2,&num3);
printf("\n The value after swapping are :\n");
printf(" element 1 = %d\n element 2 = %d\n element 3 = %d\n\n",num1,num2,num3);
return 0;
}
void swapNumbers(int *x,int *y,int *z)
{
int tmp;
tmp=*y;
*y=*x;
*x=*z;
*z=tmp;
}
Code to swap numbers using element in C++ language
#include<iostream>
using namespace std;
void cyclicSwapping(int *x, int *y, int *z) {
int temp;
temp = *y;
*y = *x;
*x = *z;
*z = temp;
}
int main() {
int x, y, z;
cout << "Input the value of 1st element : "<<endl;
cin >> x;
cout << "Input the value of 2nd element : "<<endl;
cin >> y;
cout << "Input the value of 3rd element : "<<endl;
cin >> z;
cout << "Number values before cyclic swapping..." << endl;
cout << "x = "<< x <<endl;
cout << "y = "<< y <<endl;
cout << "z = "<< z <<endl;
cyclicSwapping(&x, &y, &z);
cout << "Number values after cyclic swapping..." << endl;
cout << "x = "<< x <<endl;
cout << "y = "<< y <<endl;
cout << "z = "<< z <<endl;
return 0;
}