Write a Java Program to Find the average of elements in a queue


The Java code demonstrates how to use the Queue interface with the LinkedList class to add elements to a queue and then find the average of all elements in the queue.

  • A Queue interface is implemented using the LinkedList class to create a queue to store integers.
  • Several integer elements (10, 20, 30, 40, 50) are added to the queue using the add() method.
  • The code calculates the sum of all elements in the queue and also keeps track of the count of elements.
  • The code then calculates the average by dividing the sum by the count. To get a decimal average, the sum is cast to a double before division.
  • The average of elements in the queue is printed.

Source Code

import java.util.LinkedList;
import java.util.Queue;
 
public class QueueAverage
{
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
 
		// Adding elements to the queue
		queue.add(10);
		queue.add(20);
		queue.add(30);
		queue.add(40);
		queue.add(50);
 
		// Finding the average of elements in the queue
		int sum = 0;
		int count = 0;
 
		for (int num : queue)
		{
			sum += num;
			count++;
		}
 
		double ave = (double) sum / count;
 
		System.out.println("Average of Elements in the Queue : " + ave);
    }
}
 

Output

Average of Elements in the Queue : 30.0

Example Programs