C program to find maximum scalar product of two vectors

Maximum Scalar Product in C

Here, in this page we will discuss about the maximum scalar product in C. There we have two arrays array 1 and array 2 so here we need to find dot products of two arrays. Dot product is also known as the scalar product of two vectors.

For finding maximum scalar product of two vectors in an array. We have to multiply minimum value of array1 to the minimum value of array 2 and add all the multiplied values.

Example

Array 1- 1 2 3 4

Array 2- 2 3 4 5

Maximum scalar product= 1*2+2*3+3*4+4*5 = 2+6+12+20 = 40

maximum scalar product

Algorithm:-

  1. Input the number of elements of the arrays.
  2. Input the array 1 and array 2 elements.
  3. Initialize sum = 0.
  4. Sort the array 1 in ascending order.
  5. Sort the array 2 in ascending order.
  6. Repeat from i = 1 to n
  7. sum = sum + (arr1[i] * arr2[j])
  8. Return sum.
maximum scalar product in C

Code to find maximum scalar product in C

#include <stdio.h>

void sort(int arr[],int n){
int temp=0;
for(int i=0;i<n;i++){

for(int j=0;j<n;j++){

if(arr[i]<arr[j]){

temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;

}

}
}
}

int main()
{
int n;
printf("Enter the size of the array :");
scanf("%d",&n);

int arr1[n], arr2[n];

printf("\nEnter the elements of first array :");
for(int i=0; i<n;i++)
scanf("%d",&arr1[i]);

printf("\nEnter the elements of second array :");
for(int i=0; i<n;i++)
scanf("%d",&arr2[i]);

sort(arr1, n); //sort first array
sort(arr2, n); //sort second array

int res =0 ; // variable to hold maximum scalar product

for(int i=0; i<n; i++)
res +=(arr1[i]*arr2[i]);

printf("Maximum Scalar Product : %d", res);
return 0;
}
Output :

Enter the size of the array : 4

Enter the elements of first array : 2 3 5 7

Enter the elements of second array : 1 2 2 5

Maximum Scalar Product : 53