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

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:

  1. import java.util.Scanner;
  2.  
  3. public class Main
  4. {
  5. public static void main(String[] args) {
  6. Scanner input = new Scanner(System.in);
  7. System.out.print("a: ");
  8. int a_input = input.nextInt();
  9. System.out.print("b: ");
  10. int b_input = input.nextInt();
  11. double result = 0;
  12. for (int i = a_input; i <= b_input; i++) {
  13. if (i % 2 == 0) {
  14. result += i;
  15. }
  16. }
  17. System.out.println("Result: " + result);
  18. }
  19. }
Related Content