C++ Program to Find Sum of First n Natural Numbers

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

15 thoughts on “C++ Program to Find Sum of First n Natural Numbers”

  1. @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……..

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

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

Leave a Comment

Your email address will not be published. Required fields are marked *