Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Stack Implement in C using arrays (http://www.go4expert.com/articles/stack-implement-c-using-arrays-t24795/)

lionaneesh 29Jan2011 23:12

Stack Implement in C using arrays
 
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...

lionaneesh 30Jan2011 11:20

Re: Stack Implement in C using arrays
 
Thanks for accepting...
One more article is pending though...

About stack overflows...


All times are GMT +5.5. The time now is 21:47.