In: Computer Science
Write a function called is_valid_phone_number matches that takes two int arrays and their respective sizes, and returns the number of consecutive values that match between the two arrays starting at index 0. Suppose the two arrays are {3, 2, 5, 6, 1, 3} and {3, 2, 5, 2, 6, 1, 3} then the function should return 3 since the consecutive matches are for values 3, 2, and 5.
in C++ with explanations
CODE -
#include<iostream>
using namespace std;
// Function Prototype.
int is_valid_phone_number(int[], int, int[], int);
// Main function to test our function.
int main()
{
int arr1[] = {3, 2, 5, 6, 1, 3};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {3, 2, 5, 2, 6, 1, 3};
int size2 = sizeof(arr2) / sizeof(arr2[0]);
int num = is_valid_phone_number(arr1, size1, arr2, size2);
cout << "Number of consecutive values that match between the two arrays starting at index 0 = " << num << endl;
}
// Function Definition
int is_valid_phone_number(int arr1[], int size1, int arr2[], int size2)
{
int i=0;
// Increasing the value of i till the consequent values in both arrays are equal.
while(i<size1 && i<size2 && arr1[i] == arr2[i])
i++;
// Returning the value of i i.e. count of consecutive matching values between two arrays
return i;
}
SCREENSHOT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.