QN020. Write a program to print sum of even number between n1 to n2.


1. Objective

To print the sum of even numbers between any two given numbers.

2. Theory

In this program, we ask for the input from the user. To store the given number we use Scanner class. For loop to generate list of number between those numbers. If statement to generate even numbers.

3. Source Code
import java.util.Scanner;
public class Qn020{
public static void main(String[] args){
int 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(int i=n1;i<=n2;i++)
{
if(i%2==0)
sum+=i;
}
System.out.println("Sum of even number between " + n1 + " to " + n2 + " is " + sum);
}
}
4. Output

Enter first number: 55
Enter second number: 75
Sum of even numbers between 55 to 75 is 650

5. Conclusion

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