Stacks using 2-dimmensional array

Code to implement stacks using 2-dimmensional array.

#include<stdio.h>
int a[3][3],top=-1,m=0,n=0;

void push()
{
    int k;
    if(top==9)
        printf("stack full");
    else
    {
        printf("enter a number");
        scanf("%d",&k);
        a[m][n]=k;
        top++;
        if(n==2)
        {
            m++;
            n=0;
        }
        else
            n++;
    }
}

void pop()
{
    int k;
    if(top==-1)
        printf("stack empty");
    else
    {
        k=a[m][n-1];
        if(n==0)
        {
            m=m-1;
            n=2;
        }
        else
            n--;
        top--;
        printf("number to be deleted is: %d",k);
    }
}

void disp()
{
    int i,j,k,l;

    if(top==-1)
        printf("stack empty");
    else
    {
        if(n==0)
        {
            k=2;
            l=m-1;
        }
        else
        {
            k=n-1;
            l=m;
        }
        for(i=l;i>=0;i--)
        {
            for(j=k;j>=0;j--)
                printf("%dn",a[i][j]);
            if(n==-1)
                k=2;
        }
    }
}

int main()
{
    int ch,ch1;
    do
    {
        printf("enter 1 to push\nenter 2 to pop\nenter 3 to display ");
        scanf("%d",&ch);
        if(ch==1)
            push();
        else if(ch==2)
            pop();
        else if(ch==3)
            disp();
        else
            printf("wrong choice!!");
        printf("\npress 1 to continue");
        scanf("%d",&ch1);
    }while(ch1==1);
}
VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

14. May 2012 by Sandhi Agarwal
Categories: C Programming, Data Structures | Tags: , , , | Leave a comment

← Older posts