# C++ code?

• Aug 18th 2008, 08:28 PM
amor_vincit_omnia
C++ code?
For a homework problem I need to use a code to compute the sum of the integers from 1 to 5,000

can someone help me or direct me to another site that can? Thanks.
• Aug 18th 2008, 08:44 PM
Chris L T521
Quote:

Originally Posted by amor_vincit_omnia
For a homework problem I need to use a code to compute the sum of the integers from 1 to 5,000

can someone help me or direct me to another site that can? Thanks.

I know that C++ and Java are similar. I can give you the code to the program what you are looking for in Java, but you will need to make the proper conversion over to C++.

Code:

public class sum{     public static void main(String [] args){                       // This part computes the sum 1+2+3+...+4999+5000           int sum=0, cntr;           for (cntr=1; cntr <= 5000; cntr++)                 sum += cntr;           System.out.println (sum);     } }
I hope this somewhat helps.

--Chris
• Aug 18th 2008, 08:46 PM
Pn0yS0ld13r
I havin't programmed in awhile, but if my memory serves me correctly, it should be something like this:

Code:

int sum = 0; for(int i = 1; i >= 5000; i++) {     sum += i; }
• Aug 18th 2008, 08:52 PM
amor_vincit_omnia
Thanks to both of you guys. Chris- I don't know Java so I'm not sure how to convert? I wish we could use Matlab or Fortran.

It's been years since I've done any programming...thanks pnoy that's similar to mine. Anyone else feel free to post any ideas.
• Aug 18th 2008, 08:54 PM
o_O
Alternatively, we can use the fact that: $1 + 2 + \hdots + n = \frac{n(n+1)}{2}$. This way, we don't have to use a loop that loops 5000 times.
• Aug 18th 2008, 08:57 PM
Chris L T521
Quote:

Originally Posted by amor_vincit_omnia
Thanks to both of you guys. Chris- I don't know Java so I'm not sure how to convert? I wish we could use Matlab or Fortran.

It's been years since I've done any programming...thanks pnoy that's similar to mine. Anyone else feel free to post any ideas.

This may help. They compute the sum of the first 30 squares. Just change the code a little bit and you should get what you're looking for.

--Chris
• Aug 18th 2008, 08:58 PM
Chris L T521
Quote:

Originally Posted by o_O
Alternatively, we can use the fact that: $1 + 2 + \hdots + n = \frac{n(n+1)}{2}$. This way, we don't have to use a loop that loops 5000 times.

Why didn't I think of that? :D

--Chris
• Aug 19th 2008, 02:05 PM
arbolis
I did it in Fortran 90. For fortran 77, just put all in capital letters.
"Program notfor
implicit none

Integer :: n
Real :: z

Write(*,*)'Enter a number'