C++ program to swap 2 arrays

This C++ program swaps two integer arrays using pointers. Two arrays a[] and b[] are declared which stores the two input arrays. The pointers p1 and p2 is initially set to point to the first index of both the arrays a[] and b[]. Then the program uses a for loop to swap values in the two arrays. After swapping is complected the new arrays are displayed to the output screen.


Program



//program to swap array's using c++

#include<iostream.h>
#include<conio.h>
void main()
{
int *p1,*p2,a[50],b[50],n1,n2,i=0,t;
cout<<"Enter the size of first array: ";
cin>>n1;
p1=a;
cout<<"Enter the elements:\n";
for(i=0;i<n1;i++)
{

cin>>a[i];
}
cout<<"Enter the size of second array: ";
cin>>n2;
p2=b;
cout<<"Enter the elements:\n";
for(i=0;i<n2;i++)
{
cin>>b[i];
}
for(i=0;i<n1|i<n2;i++)
{
t=*p1;
*p1=*p2;
*p2=t;
p1++;
p2++;
}
p1=a;
p2=b;
cout<<"Arrays after swapping\n";
cout<<"Array A\n";
for(i=0;i<n2;i++)
{
cout<<*p1<<" ";
p1++;
}
cout<<"Array B\n";
for(i=0;i<n1;i++)
{
cout<<*p2<<" ";
p2++;
}
getch();
}

Output



program in c++ to swap arrays
C++ program to swap two arrays

No comments: