Java Online Compiler
Example: Sum of Even Numbers in Range in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Even Numbers in Range import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter the start of the range System.out.print("Enter the start of the range: "); int start = scanner.nextInt(); // Step 3: Prompt the user to enter the end of the range System.out.print("Enter the end of the range: "); int end = scanner.nextInt(); // Step 4: Initialize a variable to store the sum of even numbers int sumOfEvens = 0; // Step 5: Loop through each number in the given range for (int i = start; i <= end; i++) { // Step 6: Check if the current number is even // A number is even if it is perfectly divisible by 2 (remainder is 0) if (i % 2 == 0) { // Step 7: If the number is even, add it to the sum sumOfEvens += i; } } // Step 8: Print the final sum of even numbers System.out.println("The sum of even numbers in the range " + start + " to " + end + " is: " + sumOfEvens); // Step 9: Close the scanner to prevent resource leaks scanner.close(); } }
Output
Clear
ADVERTISEMENTS