The solutions are given below.
a
Insertion of data items to a stack can be done using the method push(). The snippet is given below.
for(int i=n-1;
i>=0; i--)
{ //push item to stack by push()
method
s.push('f' +
to_string(i+1));
}
The above snippet has a for loop which executes n times, where n is the total number of functions (f4, f3, etc.). Memory allocation is in the decreasing order. So, if n is 4, then f4 will be pushed to the stack first.
Inside the push function, the instruction 'f' + to_string(i+1) concatenates the character 'f' with the function number which is i+1. So, if i is 0, then it will push f1 to the stack.
b
For deleting the top item of the stack, a method called pop() can be used. The snippet is given below.
while
(!s.empty())
{ //removes the top element of
stack
s.pop();
}
The while loop checks whether the stack has enough contents before the deletion of data. If it has atleast one item, then the loop executes. Using the pop() method, the most recently pushed item will be deleted from the stack.
c
The stack top value is the last data pushed to the stack. Stack works in a Last In First Out (LIFO) manner i.e. the most recently added data will be the first one to get deleted from the stack.
Think of it like a bucket. The first item added to the bucket can only be accessed when all the items above that items are removed.
The elements of the stack are accessed through the stack top i.e. the top most element of the stack. While deleting a data item from the stack, the top element will be retrieved and removed. Now, the item below the previous top becomes the new top.
Suppose, four items are pushed to the stack i.e. f4, f3, f2 and f1. The value f1 is the recently added item. So, it is the stack top. The deletion of these items will be vthus done in the order f1, f2, f3 and f4.
The complete C++ code for the problem is given below.
#include <stdio.h>
#include<iostream>
#include <bits/stdc++.h>
#include<string>
using namespace std;
int main()
{
stack <string> s;
int n;
cout<<"Enter your roll number: ";
cin>>n;
n=n+3; //roll number + 3 is the total number of
functions
//inserting functions to stack
for(int i=n-1; i>=0; i--)
{ //push item to stack by push()
method
s.push('f' +
to_string(i+1));
}
//delete all items from stack one by one
while (!s.empty())
{ //print the top element of stack
by using top() method
cout<<s.top()<<" ";
//removes the top
element of stack
s.pop();
}
return 0;
}
If the indendations are not clear, please refer the screenshots of the code given below.
Output
Hope this helps. Doubts, if any, can be asked in the comments.
Get Answers For Free
Most questions answered within 1 hours.