Answer to Question #229775 in HTML/JavaScript Web Application for Kam

Question #229775

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.


1
Expert's answer
2021-08-27T02:03:54-0400


// 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());

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS