So this a pretty interesting program I wrote for my CS 256 class. It uses a “stack” which I don’t believe has a native implementation in c. The goal is to reverse 10 characters by putting them all on the stack in the original order and then taking them off one by one.
Please note that if you are taking CS 256 you must follow the rules for using an online resource. You must not copy and paste any code and you must fully understand anything that you use.
/*
Write a program that prompts the user to enter up to 10 characters and then
press Enter. The program reads the entered characters and prints the
characters in reverse order. Your program should use a stack and push and pop
operations on the stack.
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 10 // Defines Stack Size
// External variables
int contents[STACK_SIZE];
int top = 0;
bool is_empty(void) // Checks if the stack is empty
{
return top == 0;
}
bool is_full(void) // Checks if the stack is full
{
return top == STACK_SIZE;
}
void stack_overflow(void) // prints an error message and terminates the program
{
printf("ERROR: STACK OVERFLOW");
exit(0);
}
void stack_underflow(void) // prints an error message and terminates the program
{
printf("ERROR: STACK UNDERFLOW");
}
void push(int i) // pushes an item to the stack
{
if (is_full()) // if the stack is full, call stack overflow
stack_overflow();
else
contents[top++] = i;
}
int pop(void) // removes the top item from the stack
{
if (is_empty()) // if the stack is empty, call stack underflow
stack_underflow();
else
return contents[--top]; // returns the removed item
}
int main()
{
char ch; // initializes the variable that will get getchar()
printf("Please enter 10 characters and press ENTER: "); // prompts the user
while ((ch = getchar()) != '\n') // takes the 10 characters and pushes them to the stack
{
push(ch);
}
char returnChar; // initializes the return char
printf("In reverse order: ");
for (int i = 0; i < STACK_SIZE; i += 1) // pops all of the characters off of the stack and prints them
{
returnChar = pop();
printf("%c", returnChar);
}
}
/*
OUTPUT
Please enter 10 characters and press ENTER: 012345679 // User entered 0123456789
In reverse order: 9876543210
*/