# Algorithm and Flowchart for Stack using Arrays

(430 Views)

A Stack is one of the most common Data Structure. We can implement stack using an Array or Linked list. Stack has only one End referred as TOP. So the element can only be inserted and removed from TOP only. Hence Stack is also known as LIFO (Last In First Out). The various functions of Stack are PUSH(), POP() and PEEK().

• PUSH(): For inserting element in the Stack.
• POP(): For deleting element from the Stack.
• PEEK(): To return the top element of Stack

### Flowchart for Implementing Stack using Arrays:

#### Flowchart for Push() Operation: #### Flowchart for Pop() Operation: #### Flowchart for Peek() Operation: ### Algorithm for Implementing Stack using Arrays:

#### Algorithm for PUSH() operation in Stack using Array:

Step 1: Start Step 2: Declare Stack[MAX]; //Maximum size of Stack Step 3: Check if the stack is full or not by comparing top with (MAX-1) If the stack is full, Then print "Stack Overflow" i.e, stack is full and cannot be pushed with another element Step 4: Else, the stack is not full Increment top by 1 and Set, a[top] = x which pushes the element x into the address pointed by top. // The element x is stored in a[top] Step 5: Stop

#### Algorithm for POP() operation in Stack using Array:

Step 1: Start Step 2: Declare Stack[MAX] Step 3: Push the elements into the stack Step 4: Check if the stack is empty or not by comparing top with base of array i.e 0 If top is less than 0, then stack is empty, print "Stack Underflow" Step 5: Else, If top is greater than zero the stack is not empty, then store the value pointed by top in a variable x=a[top] and decrement top by 1. The popped element is x.

#### Algorithm for PEEK() operation in Stack using Arrays:

Step 1: Start Step 2: Declare Stack[MAX] Step 3: Push the elements into the stack Step 4: Print the value stored in the stack pointed by top. Step 6: Stop

In the above algorithm,

1. We first define a stack of max size
2. PUSH(): First, we check if the stack is full, if the top pointing is equal to (MAX-1), it means that stack is full and no more elements can be inserted we print overflow. Otherwise, we increment the top variable and store the value to the index pointed by the top variable
3. POP(): First, we check if the stack is empty, if the top variable has a value less than 0, it means the stack is empty. So, we can't delete any more elements and print underflow condition. Otherwise, we decrement the top variable.
4. PEEK(): The PEEK() function returns the topmost value stored in stack, it's done by returning the element pointed by the top variable.