My code, compiles fine in GCC.. your advices are very welcomed since i'm a beginner
/*
* Stack.c
*
* Program to demonstrate the stack concept
*
* by Ahmed M. Sha'alan, disturbed@live.com, www.thedb.com/m
*/
#include <stdio.h>
#include <stdlib.h> //for the system() and exit() functions
#define STACKSIZE 100 //the stack size
struct STACK { //stack structure
short int top;
int items[STACKSIZE];
};
typedef struct STACK stk; //a short-hand for the stack (stk badal stack y3ny :D)
int empty(stk *ptr){ //checks if the stack is empty
return(ptr->top<0?1:0); //shorter and makes more sense than the IF statment
}
int full(stk *ptr) { //checks if the stack is full
return(ptr->top>=STACKSIZE?1:0); //^^ foo2 :D
}
void push(stk *ptr, int *x) { //pushes a value to the top of the stack
ptr->items[++ptr->top]=*x;
}
int pop(stk *ptr) { //displays the top value of the stack
return (ptr->items[ptr->top--]);
}
void print_pop(stk *ptr){ //the pop() function but with empty() check and messages
if(empty(ptr))
puts(">>The stack is empty!");
else
printf(">>The last value in the stack is: %d.\n", pop(ptr));
}
void print_push(stk *ptr){ //the push() function with the checking and messages
int x;
if(full(ptr))
puts(">>The stack is full!");
else{
printf(">>Enter the value you want to push: ");
fflush(stdin); //a clever way to clear the standard input (keyboard input) to prevent weird behavoir, try to remove it and see what happens
scanf("%d", &x);
push(ptr, &x);
puts(">>done!");
}
}
void print_all(stk *ptr) { //prints all the elements in the stack
unsigned short int i=0;
system("cls");
puts("********************");
if (empty(ptr))
puts(">>The stack is empty!");
else{
for (;i<=ptr->top;i++)
printf("|%d- %d\n",i+1, ptr->items);
}
puts("********************");
}
void interface(stk *ptr) { //the "interface" lol, i KNOW it's a console aplication :D
unsigned short int choice; //we only need numbers from 1 to 4
system("cls");
puts("\n=====================================");
puts("Stack Implementation in C...");
puts("=====================================");
BEGINING:
puts("\n=======================================================");
puts("1- Press 1 for putting a value in the stack.");
puts("2- Press 2 for displaying the last value in the stack.");
puts("3- Press 3 for displaying ALL the values in the stack.");
puts("4- Press 4 for exiting the program.");
puts("=======================================================");
printf("What do you want to do? ");
fflush(stdin); //read foo2 ^ :D
scanf("%d", &choice);
puts(""); //new line
switch (choice) {
case 1:
print_push(ptr);
break;
case 2:
print_pop(ptr);
break;
case 3:
print_all(ptr);
break;
case 4:
exit(1);
default:
puts(">>Please make sure you've entered a valid option..");
break;
}
goto BEGINING; //repeat again and again til the user exits
}
int main() { //finaly the main :D
stk stack;
stack.top=-1; //sets the top to -1 for the stack to act right
interface(&stack);
return 0;
}