C++ Program to Compute Cross Product of Two Vectors

C++Server Side ProgrammingProgramming

This is a C++ program to compute Cross Product of Two Vectors.

Let us suppose,

M = m1 * i + m2 * j + m3 * k

N = n1 * i + n2 * j + n3 * k.

So, cross product = (m2 * n3 – m3 * n2) * i + (m1 * n3 – m3 * n1) * j + (m1 * n1 – m2 * n1) * k

where m2 * n3 – m3 * n2, m1 * n3 – m3 * n1 and m1 * n1 – m2 * n1 are the coefficients of unit vector along i, j and k directions.

Algorithm

Begin
   Declare a function cProduct().
      Declare three vectors v_A[], v_B[], c_P[] of the integer
      datatype.
      c_P[0] = v_A[1] * v_B[2] - v_A[2] * v_B[1].
      c_P[1] = -(v_A[0] * v_B[2] - v_A[2] * v_B[0]).
      c_P[2] = v_A[0] * v_B[1] - v_A[1] * v_B[0].
   Initialize values in v_A[] vector.
   Initialize values in v_B[] vector.
   Initialize c_P[] vector with an integer variable n.
   Print “Cross product:”.
   Call the function cProduct() to perform cross product within v_A[] and
v_B[].
   for (int i = 0; i < n; i++)
      print the value of c_P[] vector.
End.

Example Code

#include
#define n 3
using namespace std;
void crossProduct(int v_A[], int v_B[], int c_P[]) {
   c_P[0] = v_A[1] * v_B[2] - v_A[2] * v_B[1];
   c_P[1] = -(v_A[0] * v_B[2] - v_A[2] * v_B[0]);
   c_P[2] = v_A[0] * v_B[1] - v_A[1] * v_B[0];
}
int main() {
   int v_A[] = { 7, 6, 4 };
   int v_B[] = { 2, 1, 3 };
   int c_P[n];
   cout << "Cross product:";
   crossProduct(v_A, v_B, c_P);
   for (int i = 0; i < n; i++)
      cout << c_P[i] << " ";
   return 0;
}

Output

Cross product: 14 13 -5
raja
Updated on 26-Feb-2020 09:17:44

Advertisements