Computer Science Canada Adding the sum of all the numbers from 1 to 50 |
Author: | vapour99 [ Fri Sep 12, 2008 11:04 am ] |
Post subject: | Adding the sum of all the numbers from 1 to 50 |
A simple turing problem that i would appreciate help with: given this question: "Print the sum of the numbers from 50 to 0" I know that the forumla ∑(F,L)= ( L? - F? + F + L)/2 would do it but apparently this can be done in a for loop (?) anyhow; help is much appreciated; thanks in advance! |
Author: | Insectoid [ Fri Sep 12, 2008 11:18 am ] |
Post subject: | RE:Adding the sum of all the numbers from 1 to 50 |
Add the value of the for loop (the number of the variable you gave it) to a variable starting at zero. Are you doing this for school? If so, ask your teacher. Things as simple as this would only take a half minute for him/her to explain. |
Author: | octopi [ Fri Sep 12, 2008 11:20 am ] |
Post subject: | Re: Adding the sum of all the numbers from 1 to 50 |
Yes, you can do it in a for loop, but its much more efficient to use the formula method. If your teacher's making you use a for loop for this perhaps they should find an exercise where it's absolutely required to use a for loop, otherwise all they are teaching is how to do things inefficiently. Also I don't recognize that formula, it should be sum = N (First + Last) / 2 shouldn't it, so for your case it'd be 51(50) / 2 = 1275 *I don't know Turing, otherwise I'd post some Turing code for you to look at* |
Author: | Insectoid [ Fri Sep 12, 2008 11:24 am ] |
Post subject: | RE:Adding the sum of all the numbers from 1 to 50 |
Perhaps it is just to teach how to use a for loop? Learning the commands comes first; efficiency comes later. A for loop is THE simplest way to do this (in Turing). You could also use recursion, though somebody just learning might have trouble with that. Anyway, with a for loop this can be done in 4 lines. |
Author: | [Gandalf] [ Fri Sep 12, 2008 2:05 pm ] |
Post subject: | Re: RE:Adding the sum of all the numbers from 1 to 50 |
insectoid @ 2008-09-12, 11:24 am wrote: A for loop is THE simplest way to do this (in Turing).
... Anyway, with a for loop this can be done in 4 lines. The simplest way to do it is using the formula, it's just a simple expression that can be done in 1 line. It may be a bit more complicated to figure out, though. If you understand anything to do with summation though, using a for loop shouldn't be a problem at all. You go through each number up to 50 and create increase a sum variable by that value over each iteration. |
Author: | Tony [ Fri Sep 12, 2008 2:34 pm ] |
Post subject: | RE:Adding the sum of all the numbers from 1 to 50 |
Bonus points -- prove (by induction!) that the formula works. |
Author: | Insectoid [ Fri Sep 12, 2008 3:53 pm ] |
Post subject: | RE:Adding the sum of all the numbers from 1 to 50 |
Touche |