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

Question #229779


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


1
Expert's answer
2021-08-28T06:09:35-0400
//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())

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