Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 help with for loops please(add 1 to 100)
Index -> Programming, Turing -> Turing Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
dmitrip




PostPosted: Wed Feb 14, 2007 7:16 pm   Post subject: help with for loops please(add 1 to 100)

hello

i am trying to write a program that will add up the first 100 positive integers and output the sum

so like 1 + 2 + 3 + 4 + 5.....all the way to 100

this is what i got soo far

[code]
var counter,total : int
counter := 1

for i :1..100
total := i + counter

put total

end for
[code]

can anybody please tell me what i can do from here

thanks alot
Sponsor
Sponsor
Sponsor
sponsor
neufelni




PostPosted: Wed Feb 14, 2007 7:37 pm   Post subject: Re: help with for loops please(add 1 to 100)

You are making this more complicated than necessary. You don't need a counter variable, the i in the for loop acts as a counter variable. All you need is a total variable, initially set to 0. Then each time through the for loop you add the value of i to your total. Like this:
Turing:
var total : int := 0

for i :1..100
    total += i
end for

put total
Cervantes




PostPosted: Fri Feb 16, 2007 8:00 pm   Post subject: RE:help with for loops please(add 1 to 100)

Also, note that if you pair the first number with the last, the second with the second last, the third with the third last, and so on, you can get a formula.

1 + 2 + 3 + ... + 98 + 99 + 100
= (1+100) + (2+99) + (3+98) + ... + (49+52) + (50+51)
= 101 + 101 + 101 + ... + 101 + 101 <<50 terms>>
= 101 * 50
= 101 * (100 / 2)
= n*(n+1) / 2

This is the formula that Guass developed to sum the first n natural numbers.

No need for for loops!
Clayton




PostPosted: Fri Feb 16, 2007 8:42 pm   Post subject: Re: help with for loops please(add 1 to 100)

does that formula only work with a range of natural numbers from 1 to n?
Cervantes




PostPosted: Fri Feb 16, 2007 9:50 pm   Post subject: RE:help with for loops please(add 1 to 100)

Yes. However, if you want to sum up the numbers from, say 10 to 100, you'd just sum up the numbers from 1 to 100 then subtract the numbers from 1 to 9.
zylum




PostPosted: Sat Feb 17, 2007 12:09 am   Post subject: RE:help with for loops please(add 1 to 100)

also note that these are triangle numbers.

code:
T(1) = 1 =        *

T(2) = 3 =        *
                  **

T(3) = 6 =        *
                  **
                  ***

etc...
Display posts from previous:   
   Index -> Programming, Turing -> Turing Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 6 Posts ]
Jump to:   


Style:  
Search: