Write a Java program to Find the sum of all even numbers in the queue
The Java code defines a class QueueEvenSum with a method findEvenSum that finds the sum of all even numbers in a given Queue of integers.
- The findEvenSum method takes a Queue<Integer> named queue as input and returns an integer representing the sum of all even numbers.
- The method initializes a variable sum to 0. This variable will be used to store the sum of all even numbers in the queue.
- It also prints the even numbers found in the queue using System.out.print().
- 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 checks if the current num is even (i.e., its remainder when divided by 2 is 0). If num is even, it is added to the current value of sum, effectively accumulating the sum of all even numbers in the queue.
- While iterating through the queue, the method also prints the even numbers using System.out.print().
- After the loop finishes, the variable sum will hold the sum of all even numbers in the queue.
- The method returns the value of sum.
- 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 is printed using System.out.println().
- The findEvenSum method is then called with the queue as an argument, and the sum of all even numbers returned by the method is stored in the variable evenSum.
- Finally, the sum of even numbers is printed using System.out.println().
Source Code
import java.util.*;
public class QueueEvenSum
{
public static int findEvenSum(Queue<Integer> queue)
{
int sum = 0;
System.out.print("Even Numbers : ");
for (int num : queue)
{
if (num % 2 == 0)
{
sum += num;
System.out.print(" " + num);
}
}
return sum;
}
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);
int evenSum = findEvenSum(queue);
System.out.println("\nSum of Even Numbers in the Queue : " + evenSum);
}
}
Output
Original Queue : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even Numbers : 2 4 6 8 10
Sum of Even Numbers in the Queue : 30