cplusplus
.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
Tutorials
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs
Forum
Beginners
Function summing n integers
Function summing n integers
Oct 22, 2009 at 6:22pm UTC
foncused
(24)
Having trouble writing a function "compute_sum" that will ask for n input and then sum the first n integers (If 5 is entered, 5+4+3+2+1). I assume the function will need to include a loop, but do not know which to use, for, do while or just while.
Oct 22, 2009 at 6:55pm UTC
firedraco
(6243)
I would actually use a for loop, but you could use a while loop (since for loops can be changed to while loops and vice versa).
http://www.cplusplus.com/doc/tutorial/control/#loops
Oct 22, 2009 at 7:02pm UTC
foncused
(24)
Thanks, I was considering the For loop, but cant seem to figure out the code that will sum the numbers:
Its basically n + (n-1) + (n-2)....etc. until n=0
Oct 22, 2009 at 8:17pm UTC
jsmith
(5804)
for( int i = 1; i <= N; ++i )
counts from 1 to N.
You figure out the rest.
or, the sum of the first N integers is N * ( N + 1 ) / 2.
Oct 22, 2009 at 9:05pm UTC
foncused
(24)
Fair enough, I will spend some more time on it and figure out the rest on my own. Thanks firedraco and jsmith!
Topic archived. No new replies allowed.