Google Add

Search

C Program to Implement a Stack Using Array

Write a C program to implement a stack using array. In this tutorial, You are going to learn the implement of stack data structure using an array.

What is a Stack Data Structure?

A Stack is a data structure in which insertion and deletion can be done from one end only. That's why it is also called LIFO(Last In First Out).

In stack, Insertion and deletion operation is known as push (Insertion) and pop (Deletion). While inserting and deleting an element in a stack we need to check some conditions.

For insertion, we need to check whether a memory is available, if memory is not available then it is known as stack overflow. Similarly, while deleting (pop operation) an element, if no element is present in a stack, then it is known as stack underflow.





C Program to Implement a Stack Using Array



Reverse a String using Stack

C Program to Implement a Stack using Array


Let's write a c code to implement stack push and pop operation using an array.


#include <stdio.h>

#define MAX 50
int top=-1;
int arr[MAX];

void push(int item){
     
    if(top==MAX-1){
        printf("Stack Overflow");
        return;
    }else{
        //Insert the element in a stack
        arr[++top]=item;
        printf("Value inserted in stack is %d\n",item);
    }
}

void pop() {

    int val;

    if(top==-1){
        printf("Stack underflow");
        return;
    }else{
        val = arr[top];
        --top;
    }

    printf( "Value deleted from stack is %d\n",val);
}

main()
{
    
    //Inserting value in stack

    push(5);
    push(7);
    push(2);

    //Deleting value from stack

    pop();
    pop();

} 


Stack Program in C using Array - Video Tutorial




Stack push and pop operation

No comments:

Post a Comment