Monday, 31 August 2020

Sum Of Prime Numbers From Given Range

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

Input:
Enter the starting number: 
5
Enter the end number: 
20
Output:
Prime nos from Given Range :
5
7
11
13
17
19
Sum of Prime Numbers From Given Range= 72


Code in Java:

import java.util.Scanner;
public class SumOfPrimrNumbersFronGivenRange 
{
	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 count,sum=0;
		System.out.println("Prime nos from Given Range :");
		//condition used to identify number is odd or even
			for(int i=n1; i<=n2; i++)
			{
				count=0;
				for(int j=1; j<=i; j++)
				{
					if(i%j==0)
					{
						count++;
					}
				}
				if(count==2)
				{ 
					System.out.println(i);	
					sum=sum+i;
				}
			}
	System.out.println("Sum of Prime Numbers From Given Range= "+sum);
	}
}
  

Output:
Enter the starting number: 
5
Enter the end number: 
20
Prime nos from Given Range :
5
7
11
13
17
19
Sum of Prime Numbers From Given Range= 72



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