what is stack and how to implementation of stack using C in dataStructure developerIndian.com

Updated:13/08/2023 by Computer Hope

Go Back



A stack is a linear data structure in which the insertion or add of a new element and removal or delete of an existing element takes place at the same end represented as the top of the stack.

Want to learn how we can implement stack in c


    primary operations:
  • Push: Adds an element to the top of the stack.
  • Pop: Removes the top element from the stack.
    Key Concepts:
  • Top: Refers to the last added element in the stack.
  • Overflow: Occurs when pushing onto a full stack.
  • Underflow: Occurs when popping from an empty stack.

              
#include<stdio.h>
# define MAX 10
int stack [MAX], top = -1;
void  push (int  val)
  {   
   if (top == MAX -1)
       {	 
           printf("\noverflow");
	 return ;  }
   stack [++top]=val;
   }
int  pop( )
  {  
   if(top==-1)
       {  
        printf("\nunderflow");
        return -999;  }
  return stack[top--];
  }

void show ( )
   {  int i;
      if(top==-1)
        {
         printf ("\nstack is empty");
         return;  }
        for (i=top; i>=0; i--)
         printf("   %d", stack[i]);
   }




void main ()
    { int no, ch;
       do
       {	printf ("\n 1 push");
	printf ("\n 2 pop");
	printf ("\n 3 show");
	printf ("\n 0 exit");
	printf ("\n enter ur your ");
	scanf ("%d", &ch);


	switch (ch)
	 {case 1 : printf("\n Enter no : ");
		  scanf("%d", &no);
		  push(no);
		  break;
	  case 2 : no = pop( );
		  if (no != -999)
		     printf ("\n % d poped ",no);
		  break;
	  case 3 : show();
		  break;
	  case 0 : break;
	  default : printf("\n invalid choice");
	  }//end of switch
	  }while ( ch !=  0);//end of while
      }


            

Conclusion

In this article , implementation uses a stack and created method push and pop.stack is a linear data structure that follows the LIFO (Last In, First Out) principle.This means that the last element added to the stack will be the first one to be removed.