In: Computer Science
1. Write a program array_compare.c that determines the number of elements are different between the two integer arrays (same size) when compared element by element (first element with first element, second with second, and so on). The program should include the following function. Do not modify the function prototype.
void count_diff(int *a1, int *a2, int n, int *num_diff);
The function takes two integer array parameter a1 and a2 of size n. The function stores the number of elements that are different to the variable pointed by the pointer variable num_diff.
The function should use pointer arithmetic – not subscripting – to visit array elements. In other words, eliminate the loop index variables and all use of the [] operator in the function. The main function should ask the user to enter the size of the arrays and then the elements of the arrays, and then declare the arrays. The main function calls the count_diff function. The main function displays the result.
Example input/output #1: Enter the length of the array: 5
Enter the elements of the first array: -12 0 4 2 36
Enter the elements of the second array: -12 0 4 2 36
Output: The arrays are identical
Example input/output #2:
Enter the length of the array: 4
Enter the elements of the first array: -12 0 4 36
Enter the elements of the second array: 12 0 41 36
Output: The arrays are different by 2 elements
If you need any clarifications/corrections kindly comment
Please give a Thumps Up if you like the answer.
Program
#include<stdio.h>
void count_diff(int *a1, int *a2, int n, int *num_diff);
int main()
{
int a1[50],a2[50],i,n,num_diff;
printf("Enter the length of the array:");
scanf("%d",&n);
printf("Enter elements of first array:");
for(i = 0; i <n; ++i)
scanf("%d", a1 + i);
printf("Enter elements of second array:");
for(i = 0; i <n; ++i)
scanf("%d", a2 + i);
count_diff(a1,a2,n,&num_diff);
if(num_diff==0)
printf("\nThe arrays are identical\n");
else
printf("\nThe arrays are different by %d elements\n",num_diff);
return 0;
}
void count_diff(int *a1, int *a2, int n, int *num_diff)
{
int i, count=0;
for(i = 0; i < n; i++)
{
if(*a1 != *a2)
{
count++;
}
a1++;
a2++;
}
*num_diff=count;
}
Output