Sum of n Natural Numbers using For loop
Write a C++ Program to Find Sum of n Natural Numbers using For loop. Here’s simple C++ Program to Find Sum of n Natural Numbers using For loop in C++ Programming Language.
Numbers in C++
Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types.
Here is source code of the C++ Program to Find Sum of n Natural Numbers using For loop. The C++ program is successfully compiled and run(on Codeblocks) on a Windows system. The program output is also shown in below.
SOURCE CODE : :
/* C++ Program to Find Sum of n Natural Numbers using For loop */ #include<iostream> using namespace std; int main() { int i,n,sum=0; cout<<"\nHow many numbers u want :: "; cin>>n; for(i=1;i<=n;++i) { sum+=i; } cout<<"\nSum of first [ "<<n<<" ] Numbers are = "<<sum<<"\n"; return 0; }
OUTPUT : :
/* C++ Program to Find Sum of n Natural Numbers using For loop */ How many numbers u want :: 10 Sum of first [ 10 ] Numbers are = 55 Process returned 0
Above is the source code for C++ Program to Find Sum of Natural Numbers using For loop which is successfully compiled and run on Windows System.The Output of the program is shown above .
If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.
Thanks for reading the post….
Although ,this method fits well for smaller nos. it’s very hectic to sum upto large number e.g., upto 1,000,000. To reduce time complexity a better approach is being used . This approach uses simple mathematical formula to calculate sum upto n terms .
sum=[n*(n+1)]/2
Happy coding !!!