Program to do Operations like isEmpty(), isFull(), and peek() in Stack using an Array | C Code


In the previous article, we already discussed the push() and pop() operations. So, today we will learn about the isEmpty(), isFull(), and peek() operations in the stack.

isEmpty()
It is a function used in stack operations to check whether the stack contains any elements or not. That means if there is no element present in the stack, then the stack is considered to be empty.

isFull()
It is also a function used in stack data structures to check if the stack data structure has reached its maximum size.

peek()
It is a function used in the stack to access the top element of the stack without removing it. It is useful to check the element before performing the other operations.

Let's understand these operations through the below program.

Program

#include <stdio.h>
#include <stdbool.h>
#define SIZE 5

int stack[SIZE];
int top = -1;

bool isEmpty();
bool isFull();
int peek();

int main()
{
    top = 4;
    stack[0] = 10;
    stack[1] = 28;
    stack[2] = 30;
    stack[3] = 29;
    stack[4] = 56;

    printf("Is the stack empty? %s\n", isEmpty() ? "Yes" : "No");
    printf("Is the stack full? %s\n", isFull() ? "Yes" : "No");
    printf("Top element is %d\n", peek());

    return 0;
}

bool isEmpty()
{
    if (top == -1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool isFull()
{
    if (top == SIZE - 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

int peek()
{
    return stack[top];
}


Output

Is the stack empty? No
Is the stack full? Yes
Top element is 56


Comments