Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Jun 2008
    Location
    Jupiter
    Posts
    49
    Thanks
    8
    Thanked 0 Times in 0 Posts

    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

  • #2
    New Coder
    Join Date
    May 2009
    Posts
    13
    Thanks
    1
    Thanked 0 Times in 0 Posts
    PHP Code:
    for ($i=1$i<100;$i++) {
    $sum $i;
    }

    echo 
    $sum
    I think that should do it.

  • #3
    Senior Coder Len Whistler's Avatar
    Join Date
    Jul 2002
    Location
    Vancouver, BC Canada
    Posts
    1,323
    Thanks
    26
    Thanked 100 Times in 100 Posts
    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>";
      }
    ?>

    ---------
    Leonard Whistler

  • Users who have thanked Len Whistler for this post:

    tokio (05-09-2009)

  • #4
    Regular Coder
    Join Date
    Jun 2004
    Posts
    128
    Thanks
    6
    Thanked 0 Times in 0 Posts
    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. <_<
    Last edited by XtremeGamer99; 09-29-2009 at 08:30 AM.


  •  

    Posting Permissions

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