Write a Java program to Find the Product of all elements in a queue


The Java code defines a class QueueProduct with a method findProduct that finds the product of all elements in a given Queue of integers.

  • The findProduct method takes a Queue<Integer> named queue as input and returns an integer representing the product of all elements in the queue.
  • The method initializes a variable prod to 1. This variable will be used to store the product of all elements in the queue.
  • The method then iterates through the elements of 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 multiplies num with the current value of prod, effectively calculating the product of all elements in the queue.
  • After the loop finishes, the variable prod will hold the product of all elements in the queue.
  • The method returns the value of prod.
  • In the main method, a Queue<Integer> named queue is created using the LinkedList implementation of the Queue interface. Elements (integers) are added to the queue using the offer() method.
  • The original queue elements are printed using System.out.println().
  • The findProduct method is then called with the queue as an argument, and the product of all elements returned by the method is stored in the variable prod.
  • Finally, the product of all elements in the queue is printed using System.out.println().

Source Code

import java.util.*;
 
public class QueueProduct
{
	public static int findProduct(Queue<Integer> queue)
	{
		int prod = 1;
		for (int num : queue)
		{
			prod *= num;
		}
		return prod;
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(1);
		queue.offer(2);
		queue.offer(3);
		queue.offer(4);
		System.out.println("Original Queue Elements : "+queue);
 
		int prod = findProduct(queue);
		System.out.println("Product of Queue Elements : " + prod);
	}
}
 

Output

Original Queue Elements : [1, 2, 3, 4]
Product of Queue Elements : 24

Example Programs