Java Program to find sum of all prime numbers between 1 to n


In this program, You will learn how to find sum of all prime numbers between 1 to n in Java.


Sum of prime numbers upto 10th : 2 + 3 + 5 + 7 = 17


Example: How to find sum of all prime numbers between 1 to n in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int n, i, j, p = 1, s = 0;

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter Upto Prime Numbers :");
        n = sc.nextInt();

        for (j = 2; j <= n; j++) {
            p = 1;
            for (i = 2; i < j; i++) {
                if (j % i == 0) {
                    p = 0;
                    break;
                }
            }
            if (p == 1){
              s = s + j;
            }
        }
        System.out.println("\nThe Sum of All Prime Numbers is :" + s);

    }
}

Output:

Enter Upto Prime Numbers :10
The Sum of All Prime Numbers is :17