C++ program to find minimum scalar of two vectors

Finding the minimum scalar product

In this section we learn about how to  Find minimum scalar product of two array.

There are we have a two array That is array 1 and array 2  so here we need to find the dot product of the two array. Dot product is also known as the scalar product of two vector.

For finding the minimum scalar product of arrays we need to multiply the minimum value of first array to the maximum value of the second array and add these corresponding products to result.

Find minimum scalar product in Cpp
Find minimum scalar product in cpp

Algorithm:-

  1. Initialize two array.
  2. Take the element for both array,
  3. Sort the both array by calling sort method.
  4. print the minimum scalar product by calling MScalarProduct().
  5. MScalarProduct(a1,a2,n)
    1. initialize sum variable.
    2. initialize for loop from 0 to size of an array.
    3. multiply array same index element and add this with sum and store it in same variable.
    4. return the sum;
  6. sort(a1,a2,n)
    1. sort the array1 in ascending order.
    2. sort the array2 in descending order.

C++ Code:-

// C Program to find the minimum scalar product of two vectors (dot product)
#include<iostream>
using namespace std;

int sort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

int sort_des(int arr[], int n)
{
int i,j;
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (arr[i] < arr[j])
{
int a = arr[i]; 
arr[i] = arr[j];
arr[j] = a;
}
}
}
}

int main()
{
//fill the code;
int n;

cout<<"Enter the size of Vector ";
cin>>n;

int arr1[n], arr2[n];
int i;
cout<<"Enter the Elements of Vector 1";

for(i = 0; i < n ; i++)
{
cin>>arr1[i];
}
cout<<"Enter the Elements of Vector 2";

for(i = 0; i < n ; i++)
{
cin>>arr2[i];
}

sort(arr1, n);
sort_des(arr2, n);
int sum = 0;
cout<<" Minimum scalar product of Vector 1 and Vector 2 = ";

for(i = 0; i < n ; i++)
{
sum = sum + (arr1[i] * arr2[i]);
}
cout<<sum;
return 0;
}

Output:-

Enter the size of Vector 5
Enter the Elements of Vector 1
0
1
2
0
1
Enter the Elements of Vector 2
2
1
0
1
2
Minimum scalar product of Vector 1 and Vector 2 = 2