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(); System.out.println(); for(int i=2;i<r;i++) { int flag=0; for(int j=2;j<i;j++) { if(i%j==0) flag=1; } if(flag==0) { System.out.print(i+" "); sum=sum+i; } } System.out.println("Sum = "+sum); } }

Output:

{ 1 comment… read it below or add one }

it helped me a lot