Simple Stack Program using pointers in C Programming

Definition

A stack is a basic computer science data structure and can be defined in an abstract, implementation-free manner, or it can be generally defined as a linear list of items in which all additions and deletion are restricted to one end that is Top.

Simple Stack Program using pointers in C Programming

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

#define MAX_SIZE 3

void push(int i);
void pop(void);

int choice, i;
int *tos, *p1, arr_stack[MAX_SIZE];
int exit_p = 1;

int main() {

    int value;

    tos = arr_stack; /* tos points to the top of stack */
    p1 = arr_stack; /* initialize p1 */
    printf("\n Simple Stack Example - Pointers");

    do {
        printf("\nStack Pointer : Main Menu");

        printf("\n1.Push \t2.Pop \tOthers to exit : Your Choice : ");
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                printf("Enter value: ");
                scanf("%d", &value);
                push(value);
                break;
            case 2:
                pop();
                break;
            default:
                exit_p = 0;
                break;
        }
    } while (exit_p);

    return 0;
}

void push(int i) {
    if (p1 == (tos + MAX_SIZE)) {
        printf("\nStatus : Stack Overflow.\n");
    } else {
        *p1 = i;
        printf("\nPush Value : %d ", *(p1));
        p1++;
    }
}

void pop(void) {
    if (p1 == tos) {
        printf("\nStatus : Stack Underflow.\n");
        //return 0;
    } else {
        p1--;
        printf("\nPop Value : %d ", *(p1));
    }
}

Sample Output:


Simple Stack Example - Array and Pointers
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 100

Push Value : 100
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 200

Push Value : 200
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 300

Push Value : 300
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 400

Status : Stack Overflow.

Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 500

Status : Stack Overflow.

Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 2

Status : Stack Overflow.

Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 2

Pop Value : 300
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 2

Pop Value : 200
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 2

Pop Value : 100
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 2

Status : Stack Underflow.

Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 3


------------------
(program exited with code: 0)