Write the following array function in C The function must no
Write the following array function in C++:
The function must not use any function templates from the algorithms portion of the Standard C++ library.
int locateDifference(const string a1[], int n1, const string a2[], int n2);
Return the position of the first corresponding elements of a1 and a2 that are not equal. n1 is the number of interesting elements in a1, and n2is the number of interesting elements in a2. If the arrays are equal up to the point where one or both runs out, return the smaller of n1 and n2. Here\'s an example:
The function must write take at least two parameters: an array of strings, and the number of items the function will consider in the array, starting from the beginning.
Notwithstanding each function\'s behavior described below, all functions that return an int must return 1 if they are passed any bad arguments (e.g. a negative array size, or a position that would require looking at the contents of an element past the last element we\'re interested in). Unless otherwise noted, passing 0 to the function as the array size is not itself an error; it merely indicates the function should examine no elements of the array.
Solution
Hi, Please find my implementation.
Please let me know in case of any issue:
int locateDifference(const string a1[], int n1, const string a2[], int n2){
// if size of any one of the array is passed negatively
if( n1 < 0 || n2 < 0){
return -1;
}
int i = 0; // counter for a1
int j = 0; // counter fro a2
while( (i < n1) && (j < n2)){
// if current corresponding elements are not equal then return i or j
if(a1[i].compare(a2[j]) != 0){
return i;
}
i++;
j++;
}
// if all the elements of \'a1\' and \'a2\' are equal
if((i == n1) && (j == n2)){
return -1;
}
if(i == n1){ // all the elements of a1 are equal but n1 < n2, so return j
return j;
}
if( j == n2)
return i;
// i < n1 and j < n2 but a1[i] != a2[j]
return i; // or return j;
}
