Program to Find sum of N Natural Numbers

Natural Number:- Counting Numbers are known as Natural numbers.

Example:-

 1, 2, 3, 4, 5, 6.......N.

Problem statement:- Program to find the sum of N natural numbers.

Sample Input/Output:-

Sample Input First: 25                         Sample Output First: 325

Sample Input Second: 23                    Sample Output Second276

Explanation:- 

For output 1st: 1+2+3+4+6+7.......+24+25=325 

For output 2nd: 1+2+3+4+6+7.......+22+23=276 

Data requirement:-

   Input Data:- n

  Output Data:-Sum

  Additional Data:- i

Program in C
  
Here is the source code of the C Program to find the sum of first n natural numbers.

Code:

#include<stdio.h>
int main()
{
    int n, i;

    //Take input number of natural number 
    printf("Enter the N value:");
    scanf("%d",&n);
    int sum=0;

    //Calculate sum of the n natural number
    for(i=1;i<=n;i++)
    {
      sum=sum+i;
    }
    //display the sum of the n natural number
      printf("The sum of N Natural numbers is %d",sum);
}

Input/Output:
Enter the N value:25
The sum of N Natural numbers is 325

Program in C++

Here is the source code of the C++ Program that asks the user for a number n and prints the sum of the numbers 1 to n.

Code:

#include<iostream>
using namespace std;
int main()
{
    int n;

    //Take input number of natural number 
    cout<<"Enter the N value:";
    cin>>n;
    int sum=0;

     //Compute sum of the n natural number
    for(int i=1;i<=n;i++)
    {

      sum=sum+i;
    }

      //display the sum of the n natural number
      cout<<"The sum of n natural numbers is "<<sum;
}

Input/Output:
Enter the N value:23
The sum of n natural numbers is 276

Program in Java

Here is the source code of the Java Program to find the sum of n natural numbers using for loop.

Code:

import java.util.Scanner;
public class SumOfNnatrual {

public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
   int n;

    //Take input number of natural number 
    System.out.println("Enter the N value:");
    n=cs.nextInt();
    
      //Compute sum of the n natural number
    int sum=0;
    for(int i=1;i<=n;i++)
    {
      sum=sum+i;
    }
       
         //display the sum of the n natural number
      System.out.println("The sum of n natural numbers is "+sum);
cs.close();
}
}

Input/Output:
Enter the N value:
45
The sum of n natural numbers is 1035

Program in Python

Here is the source code of the Python Program to find the sum of n natural numbers using for loop.

Code:

#Take input number of natural number 
n=int(input("Enter the N value:"))

#Calculate the sum of the n natural number
sum=0
for i in range(1,n+1):
   sum=sum+i

#display the sum of the n natural number
print("The sum of n natural numbers is ", sum) 

Input/Output:
Enter the N value:55
The sum of n natural numbers is  1540 

C/C++/Java/Python Practice Question

Post a Comment

0 Comments