Written by Sai Sandeep Thota on July 14, 2013 in Java > Programming

Java Program to find Sum of Prime Numbers


Get our Latest updates delivered to your mailbox!

What is a prime number? Prime Number is a number which is greater than 1 and doesn’t have divisors other than 1 and itself. Previously we have written a Java Program to print Prime Numbers within given range, Today we are going to perform sum of Prime Numbers within given range and print the sum.

In this program we are taking one input that is <code>r</code> (range). We are using that variable for iteration. Here there are two <code>for</code> loops which do the job for us. The condition which checks Prime number is <code>if(i%j==0)</code> if it is true then we raise the flag saying that the number is not prime. If <code>i%j</code> is not equal to zero then the flag remains the same specifying that the number is prime. We use the <code>sum</code> variable to store the value of <code>i+sum</code> whenever flag is not raised.

Java Program to find Sum of Prime Numbers

import java.util.Scanner;

class primeSum {
	public static void main(String args[])
		int r, sum=0;
		System.out.print("Enter Range:");
		Scanner get = new Scanner(System.in);
		r = get.nextInt();
		for(int i=2;i<r;i++)
			int flag=0;
			for(int j=2;j<i;j++)
				System.out.print(i+" ");
		System.out.println("Sum = "+sum);

Java Program to print Sum of Prime Numbers

{ 1 comment… read it below or add one }

Bhupendra February 8, 2017 at 9:51 pm

it helped me a lot


Leave a Comment

Previous post:

Next post: