Q3) Write a function that takes two arrays and their size as inputs, and calculates their inner product (note that both arrays must have the same size so only one argument is needed to specify their size). The inner product of two arrays A and B with N elements is a scalar value c defined as follows:
N−1
c=A·B= A(i)B(i)=A(0)B(0)+A(1)B(1)+···+A(N−1)B(N−1),
i=0
where A(i) and B(i) are the ith elements of arrays A and B, respectively. For example, theinnerproductofA=(1,2)andB=(3,3)isc1 =9;andtheinnerproductofC= (2,5,4,−2,1) and D = (3,4,2,0,2) is c2 = 36.
You must use the following function prototype:
int innerProduct(int A[], int B[], int size);
Note: You must write your function prototype in a header file named libvector.h and you must write your function definition in a source file named libvector.c. We are providing you the main source file vector.c, which you can use to test your function. Do not change anything in vector.c.
#include <stdlib.h>
#include <stdio.h>
#include "libvector.h"
int main()
{
int* array1;
int* array2;
int n, c, result;
printf("Enter number of elements:\n");
scanf("%d", &n);
/* dynamic memory allocation */
array1 = (int*) malloc(n * sizeof(int));
array2 = (int*) malloc(n * sizeof(int));
printf("Enter the %d elements of vector A:\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array1[c]);
printf("Enter the %d elements of vector B:\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array2[c]);
result = innerProduct(array1, array2, n);
printf("The inner product of vectors A and B is: %d.\n", result);
return 0;
}
Put this code into "libvector.h":
int innerProduct(int A[], int B[], int size){
int i, sum=0;
for(i=0;i<size;i++){
sum+=A[i]*B[i];
}
return(sum);
}
vector.c file:
libvector.h file:
Output:
Get Answers For Free
Most questions answered within 1 hours.