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 mathematics script

1. ## Help with a simple mathematics script

I want to find the summation of the integers from 1-100. So i want to find 1+2+3+4+5+...n. The first thing i thought about issuing a for loop to print the number of terms, and i was then thinking of a function to sum up all of the terms.

PHP Code:
``` for (\$i=1; \$i<100;\$i++) { print \$i; // prints terms 1-100 }  ```
Any recommendations to find the summation of the terms? Thanks.

Tokio

• PHP Code:
``` for (\$i=1; \$i<100;\$i++) {\$sum = \$i;}echo \$sum;  ```
I think that should do it.

• This will output the results line by line. An echo outside the loop would be the final total.

PHP Code:
``` <?php  \$array = range(1,100);  foreach (\$array as \$value) {  \$sum = \$sum + \$value;  echo "\$sum<br>";  }?> ```

---------

• ## Users who have thanked Len Whistler for this post:

tokio (05-09-2009)

• Alternatively, you can use the arithmetic sequence equation:
(n/2)*(2a+(n-1)), where n = max number, a = min number.

PHP Code:
``` <?php\$a = 1;\$n = 100;\$sum = (\$n/2)*(2*(\$a)+(\$n-1));echo sum; // echos '5050'?> ```
EDIT: woah, didn't realize this topic was old. Was using the search function. <_<

•

#### Posting Permissions

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