#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    53
    Rep Power
    11

    summation function with for loop


    I'm using C, and I need to make a summation formula using a for loop. Each time the count is ++ I would like to add that to the next count ++. For example, IF my num was 4 .....1+2+3+4.....not just count=3, but count=6.
    Code:
    int add_it (int num){
     int count, sum, counter;
    
     /*test num then E(summation)*/
     if (num>0 && num<8943923){
     for(count = 0;count < num;count++){
    ...
    ...
     }
    
    }
     return (sum);
  2. #2
  3. Left due to despotic ad-min
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2003
    Posts
    1,044
    Rep Power
    13
    int add_it (int num){
    int count, sum, counter;

    sum = 0;

    /*test num then E(summation)*/

    if (num>0 && num<8943923){
    for(count = 1;count <= num;count++){
    sum += count;
    }

    }
    return (sum);
    }

    You may wish to put in additional checks for integer overflow (eg if sum grows too big to be stored in an int).

    It may also interest you to know that the sum of all integers from 1 to n is exactly n*(n+1)/2
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    53
    Rep Power
    11
    thx for the help and I was aware of the formula :) just wanted to do things differently. thanks again for help.

IMN logo majestic logo threadwatch logo seochat tools logo