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