Sunday, August 19, 2012

Implementation Of Stack Using Arrays In C

Language: C
Compiler: Turbo C

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(){
clrscr();
int stack[10],top=-1,  choice =0, entry=0, pop, i;
//insert, delete, display, underflow, overflow
while(choice!=4){
    printf("\nChoose from one of the following options:\nPress 1 to insert a number.\nPress 2 to delete a number.\nPress 3 to display a number.\nPress 4 to exit.\n\nYour choice is? ");
    scanf("%d", &choice);
    switch(choice){

    case 1:
    clrscr();
    printf("\nPlease enter the number: ");
    scanf("%d", &entry);
    if(top==9){
    printf("\nOverflow! The stack is full.\n");
    }
    else{
    stack[++top]=entry;
    clrscr();
    printf("\nYour number has been entered!\n");
    }
    break;

    case 2:
    clrscr();
    if(top==-1){
    printf("\nThe stack is empty.\n");
    }
    else{
    pop = stack[top];
    top--;
    printf("\nThe number %d has been deleted.\n", pop);
    }
    break;

    case 3:
    clrscr();
    if(top!=-1){
        for(i=0;i<=top;i++){
        printf("%d ", stack[i]);
        }
    }
    else{
    printf("\nThe stack is empty.\n");
    }
    break;

    case 4:
    exit(0);

    default:
    clrscr();
    printf("\nInvalid Entry!\n");
    //choice =0;
    break;
    }//end of switch

}//end of while
}//end of main

PS: Many improvements are possible in the program. You are welcome to suggest them in comments! :)

No comments:

Post a Comment