Write a Java program to Print the all Odd numbers in the queue


The Java code defines a class PrintOddNumbers with a method printOddNumbers that prints all odd numbers present in a given Queue of integers.

  • The printOddNumbers method takes a Queue<Integer> named queue as input and prints all odd numbers present in the queue.
  • The method uses a loop to iterate through each element in the queue using an enhanced for loop (also known as a "for-each" loop). In each iteration, the variable num takes the value of the current element from the queue.
  • Inside the loop, the code checks if num is odd (i.e., its remainder when divided by 2 is 1). If num is odd, it prints the number followed by a space using System.out.print().
  • After the loop finishes, all odd numbers present in the queue will be printed on the same line.
  • The method then uses System.out.println() to move to the next line.
  • In the main method, a Queue<Integer> named queue is created using the LinkedList implementation of the Queue interface. Integers are added to the queue using the offer() method.
  • The original queue is printed using System.out.println().
  • The printOddNumbers method is then called with the queue as an argument, and all odd numbers present in the queue are printed using System.out.print().

Source Code

import java.util.*;
 
public class PrintOddNumbers
{
	public static void printOddNumbers(Queue<Integer> queue)
	{
		System.out.print("Odd Numbers in the Queue : ");
		for (int num : queue)
		{
			if (num % 2 == 1)
			{
				System.out.print(num + " ");
			}
		}
		System.out.println();
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(1);
		queue.offer(2);
		queue.offer(3);
		queue.offer(4);
		queue.offer(5);
		queue.offer(6);
		queue.offer(7);
		queue.offer(8);
		queue.offer(9);
		queue.offer(10);
		System.out.println("Original Queue : "+queue);
 
		printOddNumbers(queue);
	}
}
 

Output

Original Queue : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Odd Numbers in the Queue : 1 3 5 7 9

Example Programs