C++ program to Find the Sum of first N natural numbers

Natural numbers

Natural number are those number  which is start from one to infinite.

A natural number is a number that occurs commonly and obviously in nature. As such, it is a whole, non-negative number.

Example: Natural number={1,2,,4,5,6,…….}.

So we will perform the calculation Operation on Natural number using C++ programming approach.

 

 

sum of n natural number

Implementation of Sum of N natural number in C++

First of all we will create the program of Sum of N natural number in C++.

So we will initialize sum=0 and n variable.and

the for loop using the iteration and sum=sum+i is using calculate this iteration.

and finally print the sum of N natural number.

Competitive Coding Techniques

Code of Sum of N natural number in C++

#include<stdio.h> //header files
using namespace std;

int main()
{
   int n, sum = 0; // varaible declaration and initialization
    cout << "Enter the natural number: ";
   cin >> n; // take user input
     
for (int i = 1; i <= n; ++i)
{
     sum = sum + i; // calculate sum using this iteration
}
   
cout << "Sum = " << sum; // print the sum of N natural number
return 0;
}
Output
Enter the natural number: 8

Sum=36

2 comments on “C++ program to Find the Sum of first N natural numbers”


  • Aditi

    import java.util.*;
    public class SumOfNumber {
    public static void main(String[] args)
    {
    try{
    Scanner sc= new Scanner(System.in);
    System.out.println(“Enter Values:”);
    int n=sc.nextInt();
    int sum=n*(n+1)/2;
    System.out.println(“Total Sum: “+sum);
    }catch(Exception e)
    {
    System.out.print(“Enter Numbers Only”);
    }
    }


  • vaishnavi Reddy k

    import java.util.*;
    public class Main
    {
    public static void main(String[] args)
    {
    Scanner in=new Scanner(System.in);
    int n=5,sum=0;
    System.out.println(“Enter the natural number”);
    for(int i=1;i<=n;i++)
    {
    sum=sum+i;
    }
    System.out.println(sum);
    }
    }