1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Stack Implement in C using arrays

Discussion in 'C' started by lionaneesh, Jan 29, 2011.

  1. lionaneesh

    lionaneesh New Member

    Stack is a LIFO[Last in first out] abstract type of data structure. The stack is mainly associated with 2 types of functions Push() and Pop(). Push() adds an item on the top of the stack and Pop() removes an item from the top of the stack.

    Implementation of Stack



    stack.c
    Code:
    #include<stdio.h>
    #include<string.h> // for strlen()
    #define STACK_LIMIT 99
    char stack[STACK_LIMIT+1]; // 1 is for null
    void pop()
    {
    	int i = 0;
    	if(strlen(stack) == 0)
    	{
    		return;
    	}
    	i = strlen(stack) - 1;
    	stack[i] = '\0';
    }
    
    void menu()
    {
    	printf("Stack Functions :- \n1. Push\n");
    	printf("2. Pop\n");
    	printf("3. Quit\n");
    }
    
    void init()
    {
    	printf("__________________________________________________\n");
    	printf("\tWelcome to stack implementation\n");
    	printf("__________________________________________________\n\n");
    	printf("The stack limit is set to %d\n",STACK_LIMIT);
    }
    
    void print_stack()
    {
    	int i=0;
    	for(i = 0 ; i < strlen(stack) ; i++ )
    	{
    		printf("_____\n");
    		printf("|%4d|",stack[i]);
    		printf("\n");
    	}
    }
    
    // This function inputs a int(data) and puts it on the top of the stack..
    
    void push(int data)
    {
    	int i=0;
    	if(strlen(stack) > STACK_LIMIT )
    	{
    		printf("Cannot Push !!! More data... Stack Full\n");
    		return;
    	}
    	i = strlen(stack);
    	stack[i] = data;
    }
    
    int main()
    {
    	int data = 0;
    	int choice=0;
    	init();
    	menu();
    	while(1)
    	{
    		printf("\tChoice : ");
    		scanf("%d",&choice);
    		if(choice == 1)
    		{
    			printf("Please enter a Number (int) :");
    			scanf("%d",&data);
    			push(data);
    
    		}
    		else if(choice == 2)
    		{
    			pop();
    		}
    		else
    		{
    			break;
    		}
    		printf("Stack contents :-\n");
    		print_stack();
    	}
    }
    
    Compiling :-
    Code:
    gcc stack.c -o stack 
    
    The code mainly uses 2 basic functions pop and push..

    The push function adds data at the end or top of the stack.. and prints "Cannot Push !!! More data... Stack Full" if the stack is full...

    The pop function removes data from the top of stack...
     
  2. lionaneesh

    lionaneesh New Member

    Thanks for accepting...
    One more article is pending though...

    About stack overflows...
     

Share This Page