In: Computer Science
how do you get the sum of all elements in a stack in c++ ?
There can be 2 approaches
1. We dont want the original stack again after calculating the sum
2. We want the original stack again after calculating the sum
In the first approach, we simply pop the elements till the stack becomes empty and add the element popped out to the sum.
In the second approach, we need to store the element popped out using another data structure, for example another stack and push the elements back to it after we have our answer.
Here is the code:
#include <iostream>
#include<stack>
using namespace std;
//Approach 1
int calc1(stack<int> s1)
{
int ans=0;
//run the loop till stack becomes empty
while(!s1.empty())
{
//add the topmost element to the answer
ans+= s1.top();
//remove the element
s1.pop();
}
return ans;
}
//Approach 2
int calc2(stack<int> s2)
{
//use another stack for storing removed elements
stack<int> temp;
int ans=0;
while(!s2.empty())
{
//add the topmost element to the answer and push it to another stack
ans+=s2.top();
temp.push(s2.top());
//remove element from original stack
s2.pop();
}
while(!temp.empty())
{
//push the elements back to obtain the original stack
s2.push(temp.top());
temp.pop();
}
return ans;
}
int main() {
stack<int> s1;
stack<int> s2;
//pushing elements into stack 1
s1.push(1);
s1.push(3);
s1.push(4);
s1.push(5);
s1.push(6);
//pushing elements into stack 2
s2.push(1);
s2.push(3);
s2.push(4);
s2.push(5);
s2.push(6);
int sum1, sum2;
//calculating sum using approach 1
sum1 = calc1(s1);
//calculating sum using approach 2
sum2 = calc2(s2);
cout<<"Sum of elements of first stack: "<<sum1;
cout<<"\nSum of elements of second stack: "<<sum2;
}