In: Computer Science
Given a queue of integers, write an algorithm and the program in c++ that, using only the queue ADT, calculates and prints the sum and the average of the integers in the queue without changing the contents of the queue.
// C++ program to calculate sum and average of the integers in the queue without changing the contents of the queue.
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q; // create an empty queue of integers
int sum = 0;
// push elements 1 to 10 in q such that 1 is at the front and 10 is at the end
for(int i=1;i<=10;i++)
q.push(i);
// create another temporary queue which is empty initially
queue<int> temp;
// loop that removes the element from q and inserts into the temporary queue and add the element to the sum
// queue removes the element from front and inserts the element at the back
// so temp will contain the element in the same order as present in q
while(!q.empty())
{
int num = q.front(); // get the front element of the queue
q.pop(); // remove the front element from the queue
sum += num; // add the num to sum
temp.push(num); // push the num to temp queue
}
// loop that continues till temp is not empty
// q will contain the element in the same order as it was present initially
while(!temp.empty())
{
q.push(temp.front()); // push the front element of temp to q
temp.pop(); // remove the front element from temp
}
// print the sum and average
cout<<"Sum : "<<sum<<endl;
cout<<"Average : "<<((double)sum)/q.size()<<endl;
return 0;
}
//end of program
Output: