Java program that uses a loop to compute the sum of all even numbers between a and b (inclusive), where a and b are inputs
Posted by Samath
Last Updated: April 03, 2022
  403

Write a Java program that uses a loop to compute the sum of all even numbers between  a and  b (inclusive), where  a and  b are inputs.

Code:

import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {
	    
	   Scanner input = new Scanner(System.in);
	   System.out.print("a: ");
	   int a_input = input.nextInt();
	   System.out.print("b: ");
	   int b_input = input.nextInt();
	   
	   
	    double result = 0;
	   for (int i = a_input; i <= b_input; i++) {
	        if (i % 2 == 0) {
		    result += i;
	    }
	}
	System.out.println("Result: " + result);
	}
}