Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

Thread: Help with a simple for loop function

1. Help with a simple for loop function

In my program, the user enters an integer. Using this integer as the upper limit, the program calculates the sum of the floors of the square roots of each integer from 1 to the supplied integer. I am making use of a for loop in my program, but am having trouble getting the desired result. Here is my current setup:
Code:
```var max = Number(prompt("enter an integer"));
var floor;
for (i=1; i<=max; i++) {
floor = Math.floor(Math.sqrt(i));
}
alert("the sum of the floors of the square roots of each integer from 1 to " + max + " is " + floor);```
When I run this with 4 as the supplied integer, the program gives me 2 as the answer. However, 5 is the actual correct answer (Math.floor(Math.sqrt(1))+Math.floor(Math.sqrt(2))+ Math.floor(Math.sqrt(3))+Math.floor(Math.sqrt(4)) produces 1+1+1+2, which is 5). What am I doing wrong?

• this line:
Code:
`floor = Math.floor(Math.sqrt(i));`
overwrites the floor variable every time the loop iterates

if you want to be adding the result, initialize floor as 0 and then add the result of your calculation to it on each iteration:

Code:
`floor += Math.floor(Math.sqrt(i));`
you can read elsewhere why alert and prompt are antiquated and generally frowned upon

• Users who have thanked xelawho for this post:

CaptainC (09-08-2013)

• Code:
```var max = Number(prompt("enter an integer"));
var floor=0;
for (i=1; i<=max; i++) {
floor = floor + Math.floor(Math.sqrt(i));
}
alert("the sum of the floors of the square roots of each integer from 1 to " + max + " is " + floor);```

• Users who have thanked DrDOS for this post:

CaptainC (09-08-2013)

• Thanks to both of you! My problem is solved.

•

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•