Sum of Even and Odd Numbers
This program calculates sum of even and odd numbers separately using for loop.
Problem Statement
Write a Java program that calculates sum of even and odd numbers from 1 to 10 using for loop.
Source Code
| 1 | public class SumEvenOdd { |
| 2 | public static void main(String[] args) { |
| 3 | int sumEven = 0, sumOdd = 0; |
| 4 | for(int i=1; i<=10; i++) { |
| 5 | if(i % 2 == 0) { |
| 6 | sumEven += i; |
| 7 | } else { |
| 8 | sumOdd += i; |
| 9 | } |
| 10 | } |
| 11 | System.out.println("Sum of even numbers = " + sumEven + " - Eduinq"); |
| 12 | System.out.println("Sum of odd numbers = " + sumOdd + " - Eduinq"); |
| 13 | } |
| 14 | } |
Program Output
Sum of even numbers = 30 - Eduinq Sum of odd numbers = 25 - Eduinq
Explanation
The program iterates numbers from 1 to 10. If divisible by 2, it adds to sumEven; otherwise, to sumOdd. This demonstrates how conditional checks inside loops can separate values into categories. Shows how for loop can calculate sum of even and odd numbers separately.