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


The Java code finds the sum of all elements in the Queue named queue. Here's how the code works:

  • A queue of integers named queue is created using the LinkedList implementation of the Queue interface.
  • Elements (integers) are added to the queue.
  • The content of the queue is printed using System.out.println().
  • The code initializes a variable sum to 0. This variable will be used to store the sum of all elements in the queue.
  • The code 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 value of num is added to the current value of sum, effectively accumulating the sum of all elements in the queue.
  • After the loop finishes, the variable sum will hold the sum of all elements in the queue.
  • The sum is then printed using System.out.println().

Source Code

import java.util.LinkedList;
import java.util.Queue;
 
public class QueueSumElements
{
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
 
		// Adding elements to the queue
		queue.add(1);
		queue.add(2);
		queue.add(3);
		queue.add(4);
		queue.add(5);
		queue.add(6);
		queue.add(7);
		queue.add(8);
		queue.add(9);
		queue.add(10);
 
		System.out.println("Queue Elements : "+queue);
 
		// Finding the sum of elements in the queue
		int sum = 0;
 
		for (int num : queue)
		{
			sum += num;
		}
 
		System.out.println("Sum of Elements in the Queue : " + sum);
    }
}
 

Output

Queue Elements : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sum of Elements in the Queue : 55

Example Programs