Here’s a Java program to find the sum of all prime numbers up to a given number:
import java.util.Scanner; public class SumOfPrimes { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int num = scanner.nextInt(); int sumOfPrimes = findSumOfPrimes(num); System.out.println("Sum of prime numbers up to " + num + ": " + sumOfPrimes); } public static int findSumOfPrimes(int num) { int sum = 0; for (int i = 2; i <= num; i++) { if (isPrime(i)) { sum += i; } } return sum; } public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } }
In this program, we first take user input for a number. We then call the `findSumOfPrimes()` method to find the sum of all prime numbers up to the given number.
The `findSumOfPrimes()` method takes an integer `num` as a parameter and returns the sum of all prime numbers up to `num`. We initialize an integer variable `sum` to 0. We use a for loop to iterate over each number from 2 to `num`. For each number, we check if it is a prime number using the `isPrime()` method. If it is a prime number, we add it to `sum`. We then return `sum`.
The `isPrime()` method takes an integer `num` as a parameter and returns a boolean indicating whether `num` is a prime number or not. We first check if `num` is less than or equal to 1, in which case it cannot be a prime number. We then use a for loop to check if `num` is divisible by any number from 2 to the square root of `num`. If it is divisible by any number, then it is not a prime number. Otherwise, it is a prime number.
At the end of the program, we print out the sum of prime numbers up to the given number.