JavaScript: Create the dot products of two given 3D vectors
JavaScript Basic: Exercise-108 with Solution
Write a JavaScript program to create the dot products of two given 3D vectors.
Note: The dot product is the sum of the products of the corresponding entries of the two sequences of numbers.
Sample Solution:
JavaScript Code:
// Function to calculate the dot product of two vectors in 3D space
function dot_product(vector1, vector2) {
var result = 0; // Initialize the variable to store the dot product result
// Loop through each component of the vectors and calculate the dot product
for (var i = 0; i < 3; i++) {
result += vector1[i] * vector2[i]; // Sum the products of corresponding components
}
return result; // Return the calculated dot product
}
// Examples of calculating dot products of given vectors
console.log(dot_product([1, 2, 3], [1, 2, 3])); // Output: 14 (1*1 + 2*2 + 3*3 = 14)
console.log(dot_product([2, 4, 6], [2, 4, 6])); // Output: 56 (2*2 + 4*4 + 6*6 = 56)
console.log(dot_product([1, 1, 1], [0, 1, -1])); // Output: 0 (1*0 + 1*1 + 1*(-1) = 0)
Output:
14 56 0
Live Demo:
See the Pen javascript-basic-exercise-109 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Function to calculate the dot product of two 3-dimensional vectors
const dot_product = (vector1, vector2) => {
let result = 0; // Variable to store the dot product result
// Loop through the vectors and calculate the dot product
for (let i = 0; i < 3; i++) {
result += vector1[i] * vector2[i]; // Compute the dot product for each element pair
}
return result; // Return the final dot product value
};
// Example usage of the function
console.log(dot_product([1, 2, 3], [1, 2, 3])); // Output: 14 (1*1 + 2*2 + 3*3 = 14)
console.log(dot_product([2, 4, 6], [2, 4, 6])); // Output: 56 (2*2 + 4*4 + 6*6 = 56)
console.log(dot_product([1, 1, 1], [0, 1, -1])); // Output: 0 (1*0 + 1*1 + 1*(-1) = 0)
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to find the number of sorted pairs formed by its elements of an given array of integers such that one element in the pair is divisible by the other one.
Next: JavaScript program to sort an array of all prime numbers between 1 and a given integer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-108.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics