Search This Blog

Thursday 17 May 2018

Introduction to Programming (CS201) - Comparing Arrays

#include <iostream>

using namespace std; //Allows computer to output data

//declare functions
int getinput(int[],int);   //function get input from user


int CompareArrays(int[], int[], int); //for comparing arrays

main() //main function begins
{
 //declare variables
const int sizeArray = 5;
int num1[sizeArray], num2[sizeArray], i, flag;

 //get input from keyboard
  cout << "Please enter five integers for the first array  \n";
  getinput(num1, sizeArray);
 
  cout << "Please enter five integers for the second array  \n";
  getinput(num2, sizeArray);
 
  cout << "\n";
  cout << "The values in the first array are : ";
for(i=0;i<sizeArray;i++)
{
cout << "\t" <<num1[i];
}


  cout << "\n";
  cout << "The values in the second array are : ";
for(i=0;i<sizeArray;i++)
{
cout << "\t" << num2[i];
}

//compare arrays
flag=CompareArrays(num1,num2,sizeArray);

if (flag==1)
{
cout << "\nBoth arrays are equal ";
}

if (flag==0)
{
cout << "\nThe arrays are not equal " ;
}

}//end of main function


//function which get inputs in the array
int getinput(int num[],int s)
{
int i;
for(i=0;i<s;i++)
cin >> num[i];
return num[i];
}

//function which compare the two arrays
int CompareArrays(int num1[], int num2[],int s)
{
int i;
int flag=0;

// compare the two arrays 
for ( i = 0 ; i < s ; i ++ )
{
if ( num1 [ i ]  != num2 [ i ] )
{

flag = 0 ; //set the flag to false
break ;
}
flag = 1; //set flag to true

}


return flag;

}

No comments:

Post a Comment