w3resource

JavaScript: Find the sum of squares of a numeric vector

JavaScript Array: Exercise-11 with Solution

Write a JavaScript program to find the sum of squares of a numerical vector.

Sample Solution:

JavaScript Code:

// Function to calculate the sum of squares of elements in an array
function sum_sq(array) {
  var sum = 0, // Initialize a variable to store the sum of squares
      i = array.length; // Initialize a variable with the length of the array

  // Iterate through the array in reverse order
  while (i--)
    // Add the square of the current element to the sum
    sum += Math.pow(array[i], 2);

  // Return the calculated sum of squares
  return sum;
}

// Output the result of the function with a sample array
console.log(sum_sq([0, 1, 2, 3, 4]));

Output:

30

Flowchart:

Flowchart: JavaScript: Display the colors entered in an array by a specific format

ES6 Version:

// Function to calculate the sum of squares of elements in an array
const sum_sq = (array) => {
  // Initialize a variable to store the sum of squares
  let sum = 0;

  // Iterate through the array in reverse order using forEach
  array.forEach((element) => {
    // Add the square of the current element to the sum
    sum += Math.pow(element, 2);
  });

  // Return the calculated sum of squares
  return sum;
};

// Output the result of the function with a sample array
console.log(sum_sq([0, 1, 2, 3, 4]));

Live Demo:

See the Pen JavaScript - Find the sum of squares of a numeric vector- array-ex- 11 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript program which prints the elements of the following array.
Next: Write a JavaScript program to compute the sum and product of an array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://w3resource.com/javascript-exercises/javascript-array-exercise-11.php