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 1^2 + 2^2 + 3^2 + 4^2 + 5^2.
b. Reimplement this program using a for loop
//a. While loop
function calculateSum(){
var x=prompt("Please enter a number");
let i=0;
let sum=0;
while (i<=x){
sum=sum+i*i;
i=i+1;
}
return sum}
alert (calculateSum())
// b. for loop
function calculateSum(){
const x = prompt("Please enter a number");
let sum = 0;
for (let i = 0; i <= x; i++) {
sum = sum + i * i;
}
return sum
}
alert(calculateSum())
Comments
Leave a comment