Write a program that uses an array to implement a stack.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <stdlib.h>
#define MAX 100  /* maximum size of stack */
int *s; /* stack will contain integers */
int N; /* top of stack */

void stackInit(int max) {
    s = malloc(max*sizeof(int));
    N = 0;
}

int stackEmpty() {
    return N == 0;
}

int stackFull() {
    return N == MAX;
}

void stackPush(int item) {
    s[N++] = item;
}

int stackPop(void) {
    return s[--N];  
}

void stackDisplay(void) {
    int i;
    for (i = N - 1; i >= 0; i--)
        printf("%d ", s[i]);
    printf("\n");
}

int main(int argc, char ** argv) {
    int i;
    stackInit(MAX);
    /* add 10 random numbers to stack */
    for (i = 0; i < 10; i++) {
        if (!stackFull())
            stackPush(rand() % 1000);
    }
    printf("Initial Contents: ");
    stackDisplay();
    /* pop 5 items off the stacks */
    for (i = 0; i < 5; i++) {
        if(!stackEmpty())
            stackPop();
    }

    printf("Contents after poping off 5 items: ");
    stackDisplay();

    free(s);
    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Initial Contents: 421 649 492 386 335 793 915 777 886 383 
Contents after poping off 5 items: 793 915 777 886 383 

Brief Explanation

  • The program starts by initializing a stack to a maximum size of 100.
  • The program iteratively push ten items to the stack using the function stackPush.
  • The function stackDisplay is used to display the items in the stack.
  • The program then iteratively pop out five items from the stack using the function stackPop
  • The statement free(s), frees up the space that was dynamically allocated to the array.

Add comment


Security code
Refresh