Tuesday, 22 August 2023

Stack Implementation in C unsing array

#include <stdio.h>

#include <stdlib.h>

#define SIZE 4


int top = -1, inp_array[SIZE];

void push();

void pop();

void show();


int main()

{

    int choice;

    while (1)

    {

        printf("\nPerform operations on the stack:");

        printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");

        printf("\n\nEnter the choice: ");

        scanf("%d", &choice);

        switch (choice)

        {

        case 1:

            push();

            break;

        case 2:

            pop();

            break;

        case 3:

            show();

            break;

        case 4:

            exit(0);


        default:

            printf("\nInvalid choice!!");

        }

    }

}

void push()

{

    int x;

    if (top == SIZE - 1)

    {

        printf("\nOverflow!!");

    }

    else

    {

        printf("\nEnter the element to be added onto the stack: ");

        scanf("%d", &x);

        top = top + 1;

        inp_array[top] = x;

    }

}


void pop()

{

    if (top == -1)

    {

        printf("\nUnderflow!!");

    }

    else

    {

        printf("\nPopped element: %d", inp_array[top]);

        top = top - 1;

    }

}


void show()

{

    if (top == -1)

    {

        printf("\nUnderflow!!");

    }

    else

    {

        printf("\nElements present in the stack: \n");

        for (int i = top; i >= 0; --i)

            printf("%d\n", inp_array[i]);

    }

}

1 comment:

  1. Output:



    1.INSERT ELEMENT:

    2.DELETE ELEMENT:

    3.VIEW TOP ELEMENT:

    4.DISPLAY STACK:

    5.CHANGE ELEMENT

    6.EXIT1



    ENTER ELEMENT TO ADD INTO STACK: :11 22 33 44 55



    1.INSERT ELEMENT:

    2.DELETE ELEMENT:

    3.VIEW TOP ELEMENT:

    4.DISPLAY STACK:

    5.CHANGE ELEMENT

    6.EXIT4

    11 22 33 44 55

    1.INSERT ELEMENT:

    2.DELETE ELEMENT:

    3.VIEW TOP ELEMENT:

    4.DISPLAY STACK:

    5.CHANGE ELEMENT

    6.EXIT2

    55 is deleted



    1.INSERT ELEMENT:

    2.DELETE ELEMENT:

    3.VIEW TOP ELEMENT:

    4.DISPLAY STACK:

    5.CHANGE ELEMENT

    6.EXIT3

    Top element is 44

    1.INSERT ELEMENT:

    2.DELETE ELEMENT:

    3.VIEW TOP ELEMENT:

    4.DISPLAY STACK:

    5.CHANGE ELEMENT

    6.EXIT5



    Enter number to change with 44:45



    1.INSERT ELEMENT:

    2.DELETE ELEMENT:

    3.VIEW TOP ELEMENT:

    4.DISPLAY STACK:

    5.CHANGE ELEMENT

    6.EXIT4

    11 22 33 45

    1.INSERT ELEMENT:

    2.DELETE ELEMENT:

    3.VIEW TOP ELEMENT:

    4.DISPLAY STACK:

    5.CHANGE ELEMENT

    6.EXIT


    ReplyDelete

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts