A stack can be executed in the CPU by analyzing an area of the computer memory to a stack operation and utilizing a processor register as a stack pointer. In this method, it is performed in a random access memory connected to the CPU.
An area of the computer memory is broken into three segments such as program, data, and stack. The address of the next instruction in the program is saved in the pointer Program Counter (PC). The Address Register (AR) points to an array of the information. SP continually influences the address of the element present at the top of the stack.
The three registers that are linked to the common bus are PC, AR, and SP. PC can read the instruction during the fetch stage. An operand is read during execute stage using the address register. An element is pushed into or popped from the stack using a stack pointer.
In the figure, the SP points to a beginning value ‘2001’. Therefore, the stack increase with decreasing addresses. The first element is saved at address 2000, the next element is saved at address 1999 and the last element is saved at address 1000.
The data register can read an element into or from the stack. It can use push operation to insert a new element into the stack.
SP ← SP – 1
K ← SP [DR]
It can insert another element into the stack, the stack pointer is decremented by 1. It can point to the address of the next location/word. A word from DR is inserted into the top of the stack using memory write operation.
It can delete an element from the stack. It can use the pop operation which is as follows −
DR ← K [SP]
SP ← SP + 1
The top element is read into the DR and then the stack pointer is decremented to point to the next element in the stack.
Two processor registers can check the stack limits. One processor register influence the upper limit (1000) and the other influence the lower limit (2001). During push operation, the SP is compared with the upper limit to check if the stack is full. During pop operation, the SP is compared with the lower limit to check if the stack is empty.