Input an empty queue and find the sum of the elements of the queue.

Share Your Love

Application Of Queue – Input an empty queue and find the sum of the elements of the queue.

Input :  7, 6, 4, 2, 7, 8
Output : 34 

Join Our Community

Join our WhatsApp Group To know more about Programming Language tips, tricks and knowledge about and how to start learning any programming language.

Algorithm find the sum of the elements of the queue:

  1. Use the emplace() function to add elements to the queue.
  2. If a queue isn’t empty, add the front member to the sum variable before popping it.
  3. Continue in this manner until the queue is empty.
  4. The sum variable should be printed.
#include <queue>
#include <iostream>
using namespace std;

int main()
{
	// variable declaration
	int sum = 0;
	
	// queue declaration
	queue<int> myqueue{};
	
	// adding elements to the queue
	myqueue.emplace(70);
	myqueue.emplace(60);
	myqueue.emplace(40);
	myqueue.emplace(20);
	myqueue.emplace(70);
	myqueue.emplace(80);

	// queue becomes 70, 60, 40, 20, 70, 80

	// calculating the sum
	while (!myqueue.empty()) {
		sum = sum + myqueue.front();
		myqueue.pop();
	}
	cout<< sum;
}

Output:

34

What’s Queue? And How to Implement it through function queue::emplace() in C++ STL?

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter