Sum of Odd Numbers with Varargs in Java
Create a Java program demonstrating a method with varargs that calculates the sum of odd numbers
- The OddSumCalculator class contains a static method named calculateOddSum that takes a variable number of integers (int... numbers) as arguments.
- Inside the method, it prints the given numbers using Arrays.toString() to display the array contents.
- It initializes a variable sum to store the sum of odd numbers and sets it initially to 0.
- It then iterates through each number in the numbers array.
- For each number, it checks if it's odd by using the condition num % 2 == 1.
- If the number is odd, it adds it to the sum.
- After iterating through all numbers, it returns the sum of odd numbers.
- In the main method, the calculateOddSum method is called with several integers as arguments.
- The sum of odd numbers is then printed to the console.
Source Code
import java.util.Arrays;
public class OddSumCalculator
{
static int calculateOddSum(int... numbers)
{
System.out.println("Given Numbers : " + Arrays.toString(numbers));
int sum = 0;
for (int num : numbers)
{
if (num % 2 == 1)
{
sum += num;
}
}
return sum;
}
public static void main(String[] args)
{
int oddSum = calculateOddSum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println("Sum of Odd Numbers : " + oddSum);
}
}
Output
Given Numbers : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sum of Odd Numbers : 25