Finding Minimum scalar product of two vectors in C

Finding Minimum scalar product in C

Here, in this page we will discuss the program to find the minimum scalar product of two vectors in C programming language. We are given with two integer array need to find the scalar product that will be minimum.

Finding-Minimum-Scalar-product-of-two-vector-in-C

Working :

  • Sort the first array in ascending order,
  • Sort the second array in descending order.
  • Declare a variable say product = 0.
  • Run a loop from index 0 to n
  • Set product += (arrr1[i]*arr2[i])
  • After complete iteration print product.
Minimum Scalar product in C

Code in C

Run
#include <stdio.h>

int main(){

   int arr1[] = {1, 2, 6, 3, 7};
   int arr2[] = {10, 7, 45, 3, 7};

   int n = sizeof(arr1)/sizeof(arr1[0]);


   //Sort arr1 in ascending order
   for(int i=0; i<n; i++){
       for(int j=i+1; j<n; j++){ if(arr1[i]>arr1[j]){
               int temp = arr1[i];
               arr1[i] = arr1[j];
               arr1[j] = temp;
           }
       }
   }

   //Sort arr2 in descending order
   for(int i=0; i<n; i++){
       for(int j=i+1; j<n; j++){
           if(arr2[i]<arr2[j]){
                int temp = arr2[i];
                arr2[i] = arr2[j];
                arr2[j] = temp;
           }
       }
    }

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

    printf("%d ", product);

}

Output

149

Comments