a. Using a while loop, write a program to calculate and print the sum of a given
number of squares. For example, if 5 is input, then the program will print 55, which
equals 12 + 22 + 32 + 42 + 52.
b. Reimplement this program using a for loop.
// WHILE LOOP
//function calculateSunGivenNumberWhile(){
// const num = prompt("Please enter a number");
// let i = 0;
// let sum = 0;
// while(i <= num){
// sum += i * i;
// i++;
// }
// return sum
//}
//alert(calculateSunGivenNumberWhile());
// FOR LOOP
function calculateSunGivenNumberFor(){
const num = prompt("Please enter a number");
let sum = 0;
for (let i = 0; i <= num; i++) {
sum += i * i;
}
return sum
}
alert(calculateSunGivenNumberFor());
Comments
Leave a comment