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


In this program, You will learn how to find the 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 the sum of all prime numbers between 1 to n in java.

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 a number:");
        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("Sum of all prime numbers:" + s);

    }
}

Output:

Enter a number:10
Sum of all prime numbers:17