Example Code:
A Simple Stack Program
// stack01.cpp : Defines the entry point for the console application.
// A simple stack program
// Matthew Martin, 2004
//Header files
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stack.h" // The code for this header file is here.
//Global variables
char stack[20];
int main(int argc, char* argv[])
{
char in, option, out;
int i;
printf("\nPlease enter 10 characters");
printf("\nHit return after each character is entered.");
for (i=0; i<10; i++)
{
fflush(stdin);
in = getch();
printf("\n%c", in);
stack[i]=in;
stack[i+1]='\0'; //place the null character at the end
}
do
{
printf("\nWould you like to:");
printf("\n1) push");
printf("\n2) pop");
printf("\n3) view whole stack");
printf("\nq) quit");
fflush(stdin);
option = getch();
switch(option)
{
case '1':
{
printf("\nEnter the number to push onto the stack: ");
fflush(stdin);
in=getch();
push(in);
break;
}
case '2':
{
out=pop();
printf("\nThe popped number is: %c", out);
break;
}
case '3': showstack();
break;
case 'q': printf("\nbye\n"); //quit program
break;
default: printf ("That option is not allowed!");
}
}while(option!='q');
return 0;
}
//push onto the stack
int push (char input)
{
int i;
for (i=19; i>0; i--)
{
stack[i]=stack[i-1];
}
stack[0]=input;
return 0;
}
//pop from the top of the stack
char pop ()
{
int i;
char output;
output = stack[0];
for (i=0; i<20; i++)
{
stack[i] = stack[i+1];
stack[i+1]='\0'; //place the null character
}
return output;
}
//print the contents of the stack to the screen
int showstack()
{
int i;
printf("\nThe stack contents:");
for(i=0; i<20; i++)
{
printf("\n\t%c", stack[i]);
if(stack[i+1]=='\0') break;
}
return 0;
}

by Matthew
Martin |