JavaScript: Compute the sum of cubes of all integer from 1 to an given integer
JavaScript Basic: Exercise-146 with Solution
Write a JavaScript program to compute the sum of cubes of all integers from 1 to a given integer.
Sample Solution:
JavaScript Code:
/**
* Function to calculate the sum of cubes up to a given number 'n'
* @param {number} n - The number up to which the sum of cubes needs to be calculated
* @returns {number} - The sum of cubes up to the given number
*/
function sum_Of_Cubes(n) {
var sumn = 0; // Variable to hold the sum of cubes
// Loop to calculate the sum of cubes up to the number 'n'
for (var i = 1; i <= n; i++) {
sumn += Math.pow(i, 3); // Add the cube of 'i' to the sum
}
return sumn; // Return the total sum of cubes
}
// Display the sum of cubes for different values of 'n'
console.log(sum_Of_Cubes(3)); // Output: 36
console.log(sum_Of_Cubes(4)); // Output: 100
Output:
36 100
Live Demo:
See the Pen javascript-basic-exercise-146 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
/**
* Function to calculate the sum of cubes up to a given number 'n'
* @param {number} n - The number up to which the sum of cubes needs to be calculated
* @returns {number} - The sum of cubes up to the given number
*/
const sum_Of_Cubes = (n) => {
let sumn = 0; // Variable to hold the sum of cubes
// Loop to calculate the sum of cubes up to the number 'n'
for (let i = 1; i <= n; i++) {
sumn += Math.pow(i, 3); // Add the cube of 'i' to the sum
}
return sumn; // Return the total sum of cubes
};
// Display the sum of cubes for different values of 'n'
console.log(sum_Of_Cubes(3)); // Output: 36
console.log(sum_Of_Cubes(4)); // Output: 100
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to find the maximum integer n such that 1 + 2 + ... + n <= a given integer.
Next: JavaScript program to compute the sum of all digits that occur in a given string.
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://w3resource.com/javascript-exercises/javascript-basic-exercise-146.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics