C++ program to swap 2d character array

This program swaps two 2d character arrays.  The limit of the two arrays are read to the variables n1 and n2. Then the program reads the strings one by one to both arrays. After reading the strings the program swaps the two arrays using a for loop and a while loop. The program uses strcpy() function to copy the string from one location to other.

Program



// Program to swap two dimensional character arrays
#include<iostream.h> #include<conio.h> #include<string.h> void main() { char a[5][10],b[5][10],t[10]; int i,j,n1,n2; cout<<"Enter the value for n1: "; cin>>n1; cout<<"Enter the value for n2: " ; cin>>n2; cout<<"Enter the strings to first array"; for(i=0;i<n1;i++) cin>>a[i]; cout<<"Enter the strings to second array"; for(i=0;i<n2;i++) cin>>b[i]; for(i=0;i<n1&&n2;i++) { strcpy(t,a[i]); strcpy(a[i],b[i]); strcpy(b[i],t); } if(i==n1) { while(i<n2) { strcpy(a[i],b[i]); i++; } } else { while(i<n1) { strcpy(b[i],a[i]); i++; } } cout<<"\nArrays after swapping\n"; cout<<"\nArray 1\n"; for(i=0;i<n2;i++) cout<<"\n"<<a[i]; cout<<"\nArray 2\n"; for(i=0;i<n1;i++) cout<<"\n"<<b[i]; getch(); }

No comments: