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:
- Input1:
- Enter the value of n: 20
- Output:1
- Sum of the first 20 natural number is: 210
- Input2:
- Enter the value of n: 10
- Output2:
- 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:
- Java Program to solve quadratic equations
- Java Program to find the greatest of three Numbers
- Java Program to Display the weekday between 1 and 7
- Java Program to Find the number of days in a Months.
- Java Program to Print character is vowel or Consonant
- Java Program to Check a year is a leap year or not
- Java Program to Check if Number is Positive or Negative