Sum of Odd Numbers
This program calculates the sum of odd numbers from 1 to 19 using for loop.
Problem Statement
Write a Java program that calculates the sum of odd numbers from 1 to 19 using for loop.
Source Code
| 1 | public class SumOdd { |
| 2 | public static void main(String[] args) { |
| 3 | int sum = 0; |
| 4 | for(int i=1; i<=19; i+=2) { |
| 5 | sum += i; |
| 6 | } |
| 7 | System.out.println("Sum of odd numbers = " + sum + " - Eduinq"); |
| 8 | } |
| 9 | } |
Program Output
Sum of odd numbers = 100 - Eduinq
Explanation
The program uses a for loop starting from 1 and increments by 2 each time to cover odd numbers. Each iteration adds the current odd number to sum. Shows how for loop can calculate sum of odd numbers.