Monday, 31 August 2020

Sum Of First N Natural Numbers(for loop)

Write a Java Program to find the Sum Of First N Natural Numbers

Input: 7
output: 28

Code in Java:

import java.util.Scanner;
public class SumOfFirstNNaturalNumers 
{
	public static void main(String[] args) 
	{
		Scanner scan = new java.util.Scanner(System.in);
		System.out.println("Enter the N: ");
		int N=scan.nextInt();
		int sum=0;
		for(int i=1; i<=N; i++)
		{
			sum=sum+i;
		}
		System.out.println("Sum of First "+ N +" Natural Numbers: ");
		System.out.println("="+sum);
	}
}
  
Output:
Enter the N: 
10
Sum of First 10 Natural Numbers: 
=55



No comments:

Post a Comment

If you have any doubts, please let me know

Pattern 31 & 32