Monday, 31 August 2020

Sum Of N Natural Numbers From Given Range

Write a Java Program to find the Sum Of N Natural Numbers From Given Range

Input:  5 to 15
output: 110

Code in Java:

import java.util.Scanner;
public class SumOfNaturalNumbersFromGivenRange 
{
	public static void main(String[] args) 
	{
		Scanner scan = new java.util.Scanner(System.in);
		System.out.println("Enter the starting number: ");
		int n1=scan.nextInt();
		System.out.println("Enter the end number: ");
		int n2=scan.nextInt();
		int sum=0;
		for(int i=n1; i<=n2; i++)
		{
			sum=sum+i;
		}
		System.out.println(sum);
	}
}
  
Output:
Enter the starting number: 
11
Enter the end number: 
20
155



Write a JAVA program to Find the Sum Of First N Natural Numbers

No comments:

Post a Comment

If you have any doubts, please let me know

Pattern 31 & 32