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.

Printable View

- August 18th 2008, 09:28 PMamor_vincit_omniaC++ 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. - August 18th 2008, 09:44 PMChris L T521
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);

}

}

--Chris - August 18th 2008, 09:46 PMPn0yS0ld13r
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;

}

- August 18th 2008, 09:52 PMamor_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. - August 18th 2008, 09:54 PMo_O
Alternatively, we can use the fact that: . This way, we don't have to use a loop that loops 5000 times.

- August 18th 2008, 09:57 PMChris L T521
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 - August 18th 2008, 09:58 PMChris L T521
- August 19th 2008, 03:05 PMarbolis
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'

Read(*,*)n

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

Write(*,*)z

end program

"