Count Odd Numbers with Varargs in Java


Write a Java program to find the count of odd numbers in a sequence using varargs

The class contains a method called countOddNumbers, which takes a variable number of integers as input. Inside this method, it iterates through each number in the input array and checks if it's odd (when divided by 2, the remainder is 1). If a number is odd, it increments a counter.

The main method is the entry point of the program. Inside main, it calls the countOddNumbers method with a list of numbers from 1 to 10 as arguments. It stores the result, which is the count of odd numbers, in a variable named count.

Finally, it prints out the result using System.out.println, displaying "Count of Odd Numbers : " followed by the calculated count of odd numbers.

Source Code

public class OddNumberCounter
{
	static int countOddNumbers(int... numbers)
	{
		int count = 0;
		for (int num : numbers)
		{
			if (num % 2 == 1)
			{
				count++;
			}
		}
		return count;
	}
 
	public static void main(String[] args)
	{
		int count = countOddNumbers(1, 2, 3, 4, 5, 6, 7, 8, 9 ,10);
		System.out.println("Count of Odd Numbers : " + count);
	}
}

Output

Count of Odd Numbers : 5

Example Programs