Java Program to display the sum of first N natural numbers

In this post, we will write two java programs to Sum of first N natural numbers. Positive integers 1,2,3,4, etc are known as natural numbers.

How the program will work?

  • The first program will take input of N number from the user.
  • After getting value N than calculates the sum using loop.

To understand these programs you should be knowledge of following Java concepts:

  • Java For loop
  • Java While loop

Example:

  1. Input1:
  2. Enter the value of n: 20
  3. Output:1
  4. Sum of the first 20 natural number is: 210
  1. Input2:
  2. Enter the value of n: 10
  3. Output2:
  4. Sum of the first 10 natural number is: 55

Example 1: Program to calculate the sum of N natural numbers using for loop

This program asks the user to enter the value of N then run the for loop till N number and add each value till loop get a break. And at the end display the addition of N numbers. In for Loop, first of all, the loop checks the condition and then enter to loop. If the number validated the condition then starts increment in the loop.

import java.util.Scanner;

public class demo {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter the value of n:");
        int N = sc.nextInt();
        int sum=0;

        for (int i=0;i<=N;i++){
            sum += i;
        }
        System.out.println("Sum of the first "+N+" natural number is: "+sum);
    }
}

Output:

Enter the value of n: 30
Sum of the first 30 natural number is: 465

Example 2: Program to calculate the sum of N natural numbers using while loop

In this program, we will use while loop to calculate the sum of N natural number. While loop first of all check condition and then enter in a loop. At last, it increments the value.

import java.util.Scanner;
public class sum_of_natural_number {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter the value of n:");
        int N = sc.nextInt();
        int sum=0;
        int i=1;

        while (i<=N){
            sum +=i;
            i++;
        }
        System.out.println("Sum of the first "+N+" natural number is: "+sum);
    }
}

Output:

Enter the value of n:20
Sum of the first 20 natural number is: 210

Recommended:

  1. Java Program to solve quadratic equations
  2. Java Program to find the greatest of three Numbers
  3. Java Program to Display the weekday between 1 and 7
  4. Java Program to Find the number of days in a Months.
  5. Java Program to Print character is vowel or Consonant
  6. Java Program to Check a year is a leap year or not
  7. Java Program to Check if Number is Positive or Negative

Leave a Comment

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