C Program: Stack Operations Project

CWC
4 Min Read

A stack is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed.

We start our code by including the header files “stdio.h” and “conio.h”. The code also has a array to hold the values and the variable top for manipulation

struct stack /* Structure definition for stack */
{
int stk[MAXSIZE];
int top;
};

There are four options given to the user for executing the stack. They are Push, Pop, Display and Exit.

while (option)
{
printf ("------------------------------------------\n");
printf (" 1 --> PUSH \n");
printf (" 2 --> POP \n");
printf (" 3 --> DISPLAY \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");

printf ("Enter your choice\n");
scanf ("%d", &choice);

Option1 will initiate the push function

Option2 will initiate the pop function

Option 3 will initiate the Display function

int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
} 

Option 4 will return the program from the loop and the main() will exit

switch (choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: return;
} 

Push function -> Its check is the stack is full or not. If not full it adds a number to the array. Else it will display the error message of “Stack is full”.

Top variable is incremented by 1 each time a value is added to the stack

Pop function -> Its check is the stack is empty or not. If not empty it pops the last number from the array. Else it will display the error message of “Stack is Empty”.

Top variable is decreased by 1 each time a value is added to the stack

int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);
}
else
{
num = s.stk[s.top];
printf ("poped element is = %d\n", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);

display function -> Its check is the stack is empty or not. If not empty the using a for loop it printa all the values of the stack. Else it will display the error message of “Stack is Empty”.

int i;
if (s.top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\nThe status of the stack is\n");
for (i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");;

The program is really simple you just need to understand the logic.

Download Source Code C Program: Stack Operations Project

[sociallocker]

C Program stack operations project CodeWithC
Password: codewithc.com

[/sociallocker]

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version