Write a program to input ten numbers from keyboard and find the sum of all even numbers and odd numbers

Here’s a Java program that inputs ten numbers from the keyboard and finds the sum of all even and odd numbers:

				
					import java.util.Scanner;

public class SumEvenOdd {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] numbers = new int[10];
        int evenSum = 0, oddSum = 0;

        // Input 10 numbers from the user
        System.out.println("Enter 10 numbers: ");
        for (int i = 0; i < 10; i++) {
            System.out.print("Number " + (i + 1) + ": ");
            numbers[i] = scanner.nextInt();
        }

        // Calculate the sum of even and odd numbers
        for (int i = 0; i < 10; i++) {
            if (numbers[i] % 2 == 0) {
                evenSum += numbers[i];
            } else {
                oddSum += numbers[i];
            }
        }

        // Output the results
        System.out.println("Sum of even numbers: " + evenSum);
        System.out.println("Sum of odd numbers: " + oddSum);

        scanner.close();
    }
}

				
			

Explanation:

  1. Scanner Initialization: A Scanner object is created to take input from the user.
  2. Array Declaration: An array numbers of size 10 is declared to store the user inputs.
  3. Input Loop: A for loop runs 10 times to take input from the user and store it in the array.
  4. Sum Calculation Loop: Another for loop iterates through the array to calculate the sums of even and odd numbers.
  5. Condition Check: Inside the second loop, each number is checked to see if it is even or odd using the modulus operator (%). If numbers[i] % 2 == 0, the number is even; otherwise, it is odd.
  6. Sum Update: Based on the condition check, the number is added to evenSum or oddSum.
  7. Output: Finally, the sums of even and odd numbers are printed.

Sample Output:

				
					Enter 10 numbers: 
Number 1: 12
Number 2: 7
Number 3: 5
Number 4: 10
Number 5: 2
Number 6: 3
Number 7: 8
Number 8: 15
Number 9: 6
Number 10: 1
Sum of even numbers: 38
Sum of odd numbers: 31

				
			

Running the Program:

To compile and run this Java program, follow these steps:

  1. Save the program in a file named SumEvenOdd.java.
  2. Open a terminal or command prompt and navigate to the directory containing the file.
  3. Compile the program using the javac compiler:
				
					javac SumEvenOdd.java

				
			

Run the compiled program using the java command:

				
					java SumEvenOdd

				
			

This will prompt you to enter ten numbers and then display the sum of even and odd numbers

Scroll to Top