Here I have given C++ program to find the sum of the first n natural numbers. First of all, I am reading the value of n and then calculating the sum using for loop.
If you have any doubts related to the program then feel free to ask in the comment section.
C++ Program to Find Sum of First n Natural Numbers
#include<iostream>
using namespace std;
int main()
{
int i,n,sum=0;
cout<<"How many numbers? ";
cin>>n;
for(i=1;i<=n;++i)
{
sum+=i;
}
cout<<"Sum="<<sum;
return 0;
}
Output:
How many numbers? 5
Sum=15
what is the output ? 🙂
outpot will be according to input of n…………if n=3 than output will be 6
ok thanks last time meri exam me aaya tha par nhi bna tha 🙁
@Dk4EvEr your welcome……………..keep visiting…………….
hey i hve seen dat some programrs do it with writing
long sum=0;
can u tell me whats that …long sum…
@varun long is a type of datatype same as int,float etc, its range is higher than int……..sum=0 means initial value of sum is 0……..
so friend what is output?
Neeraj Mishra, dude, this is old C++. I mean the turbo compiler is almost a decade old, so i suggest you start writing programs using a mordern compiler like g++,minigw,visual c++ etc..
what s the use of endl plz reply?????
@Anonymous there is no need of endl here, you can avoid it. Thanks for visiting.
plz help me to create a pic star using c++
waht is we are printing d in squar of n natural programme what is it meaning
Sum+=i ye samaj nahi aaya
Please continue giving such programs. This one was of great help to me.
is there any short cut like when we use max(a, b) we get a if a>b. similarly is there any key word in c++ like sum(a, b) then we get a+a1+a2+……+b. cause when we deal with large numbers it take lot of time to run it.
example: int n= sum(3, 8)
cout<<n
output= 33 cause 3+4+5+6+7+8= 33.