Sum of First n Natural Numbers
“Sum of First n Natural Numbers” is a basic programming exercise problem for beginners. Here, we are given a number ‘n’ and our task is to compute the sum of first ‘n’ natural numbers.
Natural Numbers: 1,2,3,………
Example (Sum of first n Natural Numbers):
INPUT: N = 5 OUTPUT: 15 Explanation: 1+2+3+4+5 = 15
There are two methods to compute the sum of first ‘n’ natural numbers:
- Using loop
- Using formula
METHOD 1: Find Sum of n natural numbers using loop
This method computes the sum of first n natural numbers in O(n).
C++ Program to compute sum of first n natural numbers is as follows:
/* C++ Program to compute sum of first n natural numbers */
#include<bits/stdc++.h>
using namespace std;
int main()
{
//Scanning the number 'n'
int n;
cout<<"Enter the number 'n' : ";
cin>>n;
//Computing the sum of first 'n' natural numbers
int sum = 0;
for(int i = 1; i <= n;i++)
{
sum = sum + i;
}
//Printing the sum of first 'n' natural numbers
cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
}
OUTPUT: Enter the number 'n' : 5 Sum of first 5 natural numbers is 15
METHOD 2: Using formula
Sum of first ‘n’ natural numbers: n*(n+1)/2.
This method computes the sum of first ‘n’ natural numbers in O(1).
C++ Program to compute sum of first n natural numbers is as follows:
/* C++ Program to compute sum of first n natural numbers */
#include<bits/stdc++.h>
using namespace std;
int main()
{
//Scanning the number 'n'
int n;
cout<<"Enter the number 'n' : ";
cin>>n;
//Computing the sum of first 'n' natural numbers
int sum = n*(n+1)/2;
//Printing the sum of first 'n' natural numbers
cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
}
OUTPUT: Enter the number 'n' : 5 Sum of first 5 natural numbers is 15
Related Posts:
- Program to Reverse a Number.
- Program to swap two Numbers.
- Program to print Fibonacci Series up to Nth Term.
- Program to find and print nth Fibonacci number.
- Program to find Power of the Number.
- Program to find Quotient and Remainder.
- Program to find largest amongst three numbers.
- Program to find factorial of a number.
- Program to find GCD of two numbers.
- Program to find LCM of two numbers.
- Program to check whether entered number is odd or even.
- Program to check whether entered number is prime number or not.
- Program to check whether entered number is palindrome or not.
- Program to check whether entered number is Armstrong Number or Not.
- Program to convert binary number to octal number.
- Program to convert binary number to decimal number.
- Program to convert binary number to hexadecimal number.
- Program to convert octal number to binary number.
- Program to convert octal number to decimal number.
- Program to convert octal number to hexadecimal number.