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:
- Use the emplace() function to add elements to the queue.
- If a queue isn’t empty, add the front member to the sum variable before popping it.
- Continue in this manner until the queue is empty.
- 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?