Sunday, January 25, 2015

C++ Program for comparing two arrays

#include<iostream>
#include<iomanip> //for setw()
using namespace std;
/*Function prototype*/
int compareArrays(int arr1[], int size1, int arr2[], int size2); //Function for comparing arrays

int main()
{
int arr1[50],arr2[50], //defining arrays of large sizes(50 each)
size1,size2,
result,
i;
cout << "Enter size of Array 1: ";
cin >> size1; //getting size for array 1
while(size1<1||size1>50) //applying condition if the entered size is in the available range
{
cout << "Wrong input(should be between 1to50)!\n"
<< "Enter again: ";
cin >> size1;
}
cout << "Enter size of Array 2: ";
cin >> size2; //getting size for array 2
while(size2<1||size2>50) //applying condition if the entered size is in the available range
{
cout << "Wrong Input(should be between 1to50)!\n"
<< "Enter again: ";
cin >> size2;
}
cout << "Enter elements of Array 1\n";
for( i=0 ; i<size1 ; i++ ) //for getting input for individual array elements
{
cout << "Enter element "
<< (i+1)
<< ": ";
cin >> arr1[i]; //getting value for each elemnt of array
}
cout << "Enter elements of Array 2\n";
for( i=0 ; i<size2 ; i++ ) //for getting input for individual array elements
{
cout << "Enter element "
<< (i+1)
<< ": ";
cin >> arr2[i]; //getting value for each elemnt of array
}
result=compareArrays(arr1,size1,arr2,size2); //calling function by passing arrays and their sizes
//printing the array elements in a proper formate
cout << "\nThe arrays are...\n";
cout << setw(25) << "Array1\n"; //for printing at a proper place
cout << "Index: ";
for( i=0 ; i<size1 ; i++ )
{
cout << setw(9) << i; //printing indexes
}
cout << endl
<< "Values: ";
cout << setw(8);
for( i=0 ; i<size1 ; i++ )
{
cout << arr1[i] << setw(9); //printing array 1 elements
}
cout << endl;
cout << setw(25) << "Array2\n";
cout << "Index: ";
for( i=0 ; i<size2 ; i++ )
{
cout << setw(9) << i; //printing indexes
}
cout << endl
<< "Values: ";
cout << setw(8);
for( i=0 ; i<size2 ; i++ )
{
cout << arr2[i] << setw(9); //printing array 2 elements
}
cout << endl;
//testing condition if the arrays are equal or some other condition
if(result==0)
cout << "Both the arrays are equal.\n";
else if(result==1)
cout << "Array 1 is greater than array 2.\n";
else
cout << "Array 2 is greater than array 1.\n";

return 0;
}
/*Function Definition*/
int compareArrays(int arr1[], int size1, int arr2[], int size2)
{
if( size1>size2 ) //testing if first array is greater than second array
return 1;
else if(size1<size2) //testing if second array is greater than first array
return -1;
else //will execute if sizes of both arrays are equal
{
for( int i=0 ; i<size1 ; i++ )
{
if(arr1[i]>arr2[i]) //if first array element is greater than that of second array then return 1
return 1;
else if(arr1[i]<arr2[i]) //if second array element is greater than that of first array then return -1
return -1;
}
return 0; //return 0 if elements of both arrays are equal
}
}

No comments:

Post a Comment