May 11, 2023

Stacks Using Structures

This is a description

Recommended Video - https://www.youtube.com/watch?v=73gK0cdtZ4k

#include <stdio.h>

struct stk {
    int * arr[100];
    int top;
} arr;

void push();
void pop();
void display();

void main() {
    int choice, num, i;
    struct stk *ptr = &arr;

    printf("Enter number of elements: ");
    scanf("%d", &num);

    for (i = 0; i < num; i++) {
        scanf("%d", &ptr->arr[i]);
    }
    (*ptr).top = (*ptr).arr[num-1];

    display(ptr, num);

    while (1) {
        printf("\n--- STACK OPERATIONS ---");
        printf("\n 1. Push Element");
        printf("\n 2. Pop Element");
        printf("\n 3. Display Elements");
        printf("\n 4. Exit.");

        printf("\n\n Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
        case 1:
            push(ptr, num);
            num += 1;
            break;
        case 2:
            pop(ptr, num);
            num -= 1;
            break;
        case 3:
            display(ptr, num);
            break;
        case 4:
            exit(0);
        default:
            printf("\n Wrong choice! \n");
        }
    }
}

void push(struct stk *ptr, int num) {
    int ele;
    printf("\n Enter new element: ");
    scanf("%d", &ele);

    (*ptr).arr[num] = ele;
    (*ptr).top = num+1;
    printf("Element pushed!");
    display(ptr, num+1);

}

void pop(struct stk *ptr, int num) {
    printf("Element popped (%d)!", ptr->arr[num-1]);
    (*ptr).top = num-1;
    display(ptr, num-1);
}

void display(struct stk *ptr, int num) {
    int i;
    printf("\n Stack is: \n");
    for (i = 0; i < num; i++) {
        printf(" %d,", ptr->arr[i]);
    }
    printf("\n Top is: %d \n", ptr->top);
}