Saturday, 20 September 2014

Swap value between two Arrays in C++ programming

In our previous programming we know how swap variables value. Now we will try same program but using Array. As we know that an array is set of data. So when we are talking about swap value between arrays, so in this case we need to swap more than 1 value. For example there are two array A[] and B[],
A[]=1,2,3 and B[]=4,5,6
So after swap we get
A[]=4,5,6 and B[]=1,2,3
Now let’s write the program
#include<iostream>
using namespace std;
main()
{
    int a[10],b[10],i;
    cout<<"Enter the Element in Array 1\n";
    for(i=0;i<4;i++)
    {
        cout<<"Enter your value: ";
        cin>>a[i];
    }
    cout<<"Enter the Element in Array 2\n";
    for(i=0;i<4;i++)
    {
        cout<<"Enter your value: ";
        cin>>b[i];
    }
    cout<<"Before swap\n";
    for(i=0;i<4;i++)
    {
        cout<<"a"<<i<<"= "<<a[i]<<"\n";
    }
    cout<<"and\n";
    for(i=0;i<4;i++)
    {
        cout<<"b"<<i<<"= "<<b[i]<<"\n";
    }
    int temp;
    for(i=0;i<4;i++)
    {
        temp=a[i];
        a[i]=b[i];
        b[i]=temp;
    }
    cout<<"After swap\n";
    for(i=0;i<4;i++)
    {
        cout<<"a"<<i<<"= "<<a[i]<<"\n";
    }
    cout<<"and\n";
    for(i=0;i<4;i++)
    {
        cout<<"b"<<i<<"= "<<b[i]<<"\n";
    }
}
In above program we set the array size to 4 for both of them. Now it is important to have same size for both of them. If size not match then this program should return error. Now let’s see the output
Enter the Element in Array 1
Enter your value: 1
Enter your value: 2
Enter your value: 3
Enter your value: 4
Enter the Element in Array 2
Enter your value: 5
Enter your value: 6
Enter your value: 7
Enter your value: 8
Before swap
a0= 1
a1= 2
a2= 3
a3= 4
and
b0= 5
b1= 6
b2= 7
b3= 8
After swap
a0= 5
a1= 6
a2= 7
a3= 8
and
b0= 1
b1= 2
b2= 3
b3= 4



0 comments:

Post a Comment