Tuesday, January 29, 2019

This C language code is for demonstrating how stack operations are done.

Program 1. Program to organize stack.

#include<stdio.h>
#define maxsize 10
int top=-1;
int stk[maxsize];
void pop()
{
    if(top==-1)
        printf("The stack is empty.");
    else
    {
    stk[top]=NULL;
    top--;
    system("cls");
    printf("Item popped.");
    }
    return;
}
void push(int n)
{
    if(top==maxsize-1)
        {
            system("cls");
            printf("The stack is full. Can't push any more items.");
        }
    else
    {
        top++;
        stk[top]=n;
        system("cls");
    }
    return;
}
void display()
{
    int i;
    if(top==-1)
        printf("The stack is empty");
    else
    {
        for(i=0; i<=top; i++)
        printf("%d: %d\n",i,stk[i]);
    }
    return;
}
int main()
{
    int num, ch;

    start:

    printf("Do you want to\n1.Pop\n2.Push\n3.Display\n");
    scanf("%d",&ch);

    switch (ch)

    {
        case 1:
            {
                pop();
                goto start;
            }
        case 2:
            {
                printf("Enter your input: ");
                scanf("%d",&num);
                push(num);
                goto start;
            }
        case 3:
            {
                display();
                goto start;
            }
        default:
            {
                system("cls");
                printf("Wrong input, try again");
                goto start;
            }
    }
}
That's all. Please like my page for updates. 

No comments:

Post a Comment