Total newbie question
 CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

1. Junior Member
Join Date
Sep 2003
Location
Seattle, WA
Posts
16

## Total newbie question

Could someone show me how to add the numbers 1 thru 50 and display the total of 1275 the easy way. My brain wont close in on this one and I dont want to use a ton of variables.

trip7

2. Junior Member
Join Date
Sep 2003
Location
So Cal
Posts
7
you mean something like this?

long count = 0;

for( long i = 0; i <= 50; i++)
count += i;

3. Code:
```int result = 0;
for(int i = 0 ; i < 51 ; i ++ )
{
result += i ;
}```
thats it...
'result' is 1275

4. sum = (50*51)/2= 25*51

5. Junior Member
Join Date
Sep 2003
Location
Seattle, WA
Posts
16
Exactly what I was looking for and thanks for your help all!

6. P.S.

in general the sum of the numbers from 1 to n is

sum = n*(n+1)/2

and in general to sum the numbers from m to n with 1 <= m < n

sum = (m+n)(m-n+1)/2

proof

write the sum in two ways

sum = m + (m+1) + (m+2) +...+ (n-2) + (n-1) + n
sum = n + (n - 1) + (n - 2)+...+ (m+2) + (m+1) + m

2*sum = (m+n)+(m+n)+(m+n)+...+(m+n)+(m+n)+(m+n)

How many terms are on the right? (m-n+1)

so
2*sum = (m+n)(m-n+1)

and it done
Last edited by souldog; September 30th, 2003 at 11:40 PM.

7. Originally posted by souldog
sum = (50*51)/2= 25*51
well i alwasys thought...there is a vast difference between experience+coolness and education...

cool Mr.Souldog....expected a cool answer from you like above..

now comes the formula.....cool!!!!

8. Junior Member
Join Date
Sep 2003
Location
So Cal
Posts
7
Of course, there is always a good way and an excellent way of doing something

#### Posting Permissions

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