1. ## 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.

2. 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

3. 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;
}

4. 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.

5. 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.

6. 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

7. 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?

--Chris

8. 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'

z=(n*(n+1))/2

Write(*,*)z

end program
"