Write a Java Program to find Sum of Prime Numbers using For Loop, While Loop, and Functions.
Java Program to find Sum of Prime Numbers using For Loop
This program allows the user to enter any integer value. Next, it finds the sum of all Prime numbers from 1 to 100 using For Loop.
TIP: Please refer Java Program to Check Prime Number article in Java to understand the steps involved in checking Prime Number
// Java Program to Print Prime Numbers from 1 to N public class PrintPrimeNumbers1 { public static void main(String[] args) { int i, number, count, sum = 0 for(number = 1; number <= 100; number++) { count = 0; for (i = 2; i <= number/2; i++) { if(number % i == 0) { count++; break; } } if(count == 0 && number != 1 ) { sum = sum + number; } } System.out.println("\n The Sum of Prime Numbers from 1 to 100 = " + sum); } }
Java Program to calculate Sum of Prime Numbers using While Loop
This Java program calculates the sum of prime numbers between 1 and 100 using While Loop.
// Java Program to Print Prime Numbers from 1 to N public class PrintPrimeNumbers2 { public static void main(String[] args) { int i, number = 1, count, sum = 0 while(number <= 100) { count = 0; i = 2; while(i <= number/2 ) { if(number % i == 0) { count++; break; } i++; } if(count == 0 && number != 1 ) { sum = sum + number; } number++; } System.out.println("\n The Sum of Prime Numbers from 1 to 100 = " + sum); } }
The Sum of Prime Numbers from 1 to 100 = 1060
We just replaced the For Loop in the above Java example with the While loop. If you don’t understand the While Loop, please refer: WHILE LOOP.
Program to find Sum of Prime Numbers using Method
This Java program accepts the Minimum and maximum values from the user. Next, it finds the sum of all prime numbers between the minimum and maximum value.
// Java Program to Print Prime Numbers between Minimum and Maximum import java.util.Scanner; public class PrintPrimeNumbers3 { private static Scanner sc; public static void main(String[] args) { int number, minimum, maximum, i, count, sum = 0; sc = new Scanner(System.in); System.out.print(" Please Enter the Minimum value : "); minimum = sc.nextInt(); System.out.print(" Please Enter the Maximum value : "); maximum = sc.nextInt(); for(number = minimum; number <= maximum; number++) { count = 0; for (i = 2; i <= number/2; i++) { if(number % i == 0) { count++; break; } } if(count == 0 && number != 1 ) { sum = sum + number; } } System.out.println("\n The Sum of Prime Numbers = " + sum); } }
Please Enter the Minimum value : 10
Please Enter the Maximum value : 500
The Sum of Prime Numbers = 21519