Write a C++ function to sum n natural numbers starting from a given number. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Write a C++ function to sum n natural numbers starting from a given number.

C++, function program

26th Feb 2018, 1:43 PM
Pritam Kumar
Pritam Kumar - avatar
5 Answers
+ 28
#include<iostream> using namespace std; int main() { int sum(int); int n,s=0; cout<<"How many natural numbers? "; cin>>n; s=sum(n); cout<<"Sum="<<s; return 0; } int sum(int a) { int S; S=(a*(a+1)/2); return (S); }
26th Feb 2018, 3:26 PM
Surbhi
Surbhi - avatar
+ 27
I think you wanted a program like this 😅 https://code.sololearn.com/c5IBcpDD2hbZ/?ref=app
27th Feb 2018, 12:43 AM
Surbhi
Surbhi - avatar
+ 1
That's a simple for loop where the given number is the sum and n is the end condition. And in the body it has sum += [running variable]
26th Feb 2018, 2:02 PM
Alex
Alex - avatar
+ 1
nice job, Euler ^^
26th Feb 2018, 3:29 PM
Alex
Alex - avatar
+ 1
But he asked for another starting point. Easy to add this though. (Sum until end point)-(sum until start point) should do it
26th Feb 2018, 3:32 PM
Alex
Alex - avatar