You are on page 1of 5

APPLICATIONS OF STACK:

Storing Function Calls

GROUP 6
Ogunmola Wemimo Ezeilo Chijioke Oritogun Keren-Happoch Oga Stephen O. Olapojoye Rukayat T. Adeleke Oladapo Phil Abimbola Olawale Z. Ebebe Grace-Angelica A. Akanbi Olanrewaju Okonkwo Odera M. Kanu Francis Obinna 149505 149471 151283 151188 151238 150983 150965 151090 151027 149517 151150

EXPLANATION When a function is called in C++, 1. An Activation Record (AR) is created. 2. The AR is then pushed into the function call stack. 3. If the function calls any other function, the AR of this second function is also pushed into the function call stack. 4. The last function to enter into the stack will be the first to be popped. In the program belows, the main function performs a call to functionA which in turn calls functionB and this continues up till functionE.

ILLUSTRATION OF PUSH AND POP IN STACK

PUSH

functionE functionD functionC functionB functionA

POP

Function call stack works with a last-in-first-out (LIFO) mechanism, that is the last function call in the stack executes first and the first function call in the stack will be the last to be executed. This unwinding of multiple function calls is one of the various applications of the stack data structure.

THE CODE
#include<iostream> #include<string> #include<stack> using namespace std; stack<string> myStack; void functionB(); void functionC(); void functionD(); void functionE(); void functionA() { cout << "Function A is pushed into stack.\n"; myStack.push("Function A pops.\n"); functionB(); } void functionB() {

cout << "Function B is pushed into stack.\n"; myStack.push("Function B pops.\n"); functionC(); } void functionC() { cout << "Function C is pushed into stack.\n"; myStack.push("Function C pops.\n"); functionD(); } void functionD() { cout << "Function D is pushed into stack.\n"; myStack.push("Function D pops.\n"); functionE(); void functionE() { cout << "Function E is pushed into stack.\n"<<endl;

myStack.push("Function E pops.\n"); while(!myStack.empty()){ cout << myStack.top(); cout << endl; myStack.pop();

} } int main() { functionA(); system("PAUSE"); return 0; }

SCREENSHOT OF THE PROGRAMS OUTPUT


}

You might also like