Implement a Stack as an Array - C Data Structure

C examples for Data Structure:Stack

Description

Implement a Stack as an Array

Demo Code

#include <stdio.h>
#include <stdlib.h>
#define STACKSIZE 8/*  w  w w .  jav  a 2  s . c  om*/

int stack[STACKSIZE];
int intTop = 0;
int stackMenu(void);
void displayStack(void);
void popItem(void);
void pushItem(void);

int main(){
  int intChoice;
  do {                          /* do-while statement begins */
    intChoice = stackMenu();
    switch(intChoice) {         /* switch statement begins */
      case 1:
        pushItem();
        break;
      case 2:
        popItem();
        break;
      case 3:
        displayStack();
        break;
      case 4:
        exit(0);
    }                           /* switch statement ends */
    fflush(stdin);
  } while(1);                   /* do-while statement begins */
}

int stackMenu()
{
  int intChoice;
  printf("\n Enter 1 to Push an Element onto Stack. ");
  printf("\n Enter 2 to Pop an Element from Stack. ");
  printf("\n Enter 3 to Displays the Stack on the Screen.");
  printf("\n Enter 4 to Stop the Execution of Program.");
  printf("\n Enter your choice (0 <= N <= 4): ");
  scanf("%d", &intChoice);
  return intChoice;
}

void displayStack()
{
  int j;
  if(intTop == 0) {
    printf("\n\nStack is Exhausted.");
    return;
  }
  else {
    printf("\n\nElements in stack:");
    for(j=intTop-1; j > -1; j--)
    printf("\n%d", stack[j]);
  }
}

void popItem()
{
  if(intTop == 0) {
    printf("\n\nStack is Exhausted.");
    return;
  }
  else
    printf("\n\nPopped Element: %d ", stack[--intTop]);
}

void pushItem()
{
  int intData;
  if(intTop == STACKSIZE) {
    printf("\n\nStack is Completely Filled.");
    return;
  }
  else {
    printf("\n\nEnter Element K (0 <= K <= 30000) : ");
    scanf("%d", &intData);
    stack[intTop] = intData;
    intTop = intTop + 1;
    printf("\n\nElement Pushed into the stack");
  }
}

Result


Related Tutorials