QN022. Write a program to print sum of prime numbers between n1 to n2.


1. Objective

To print the sum of prime number between two given numbers

2. Theory

In this program, we ask for the user to input two numbers. We use Scanner clas to store the given numbers. For loop to generate list of numbers and some if statements to check for the prime or not.

3. Source Code
import java.util.Scanner;
public class Qn022{
public static void main(String[] args){
int number,sum=0;
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
int n1 = input.nextInt();
System.out.print("Enter second number: ");
int n2 = input.nextInt();
for(number=n1; number<=n2; number++)
{
int count=0;
for(int i=2; i<=number/2; i++)
{
if(number%i==0)
{
count++;
break;
}
}
if(count == 0 && number != 1)
sum+=number;
}
System.out.print("Sum of prime number between " + n1+ " to " + n2 + " is " + sum);
}
}
4. Output

Enter first number: 100
Enter second number: 250
Sum of prime numbers between 100 to 250 is 4770

5. Conclusion

In this way, I would like to conclude that, we can calculate sum of prime numbers between any two any given numbers using this program.