Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! π πΉLearn advanced coding techniques in C& C++ πΉMaster Linux internals & shell scripting πΉDeep dive into Data Structures & Algorithms πΉExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) πΉGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
Stack Operations in C Using Array
✅ Stack Operations in C Using Array
#include<stdio.h>
#define size 5
int top = -1;
int stack[size];
int isempty()
{
return (top == -1);
}
int isfull()
{
return (top == size - 1);
}
void push(int value)
{
if(isfull())
{
printf("Stack overflow\n");
}
else
{
stack[++top] = value;
printf("%d added successfully to stack\n", value);
}
}
void pop()
{
if(isempty())
{
printf("Stack underflow\n");
}
else
{
printf("%d popped from stack\n", stack[top--]);
}
}
void peek()
{
if(isempty())
{
printf("Stack is empty\n");
}
else
{
printf("Top element is %d\n", stack[top]);
}
}
void display()
{
if(isempty())
{
printf("Stack is empty\n");
}
else
{
printf("Stack elements are:\n");
for(int i = top; i >= 0; i--)
{
printf("%d\n", stack[i]);
}
}
}
int main()
{
int choice, data;
while(1)
{
printf("\n1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter data: ");
scanf("%d", &data);
push(data);
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
display();
break;
case 5:
return 0;
default:
printf("Invalid choice\n");
}
}
}
π Explanation:
This C program implements stack operations using an array. A stack follows the LIFO (Last In First Out) principle.
- Push: Adds an element to the top of the stack.
- Pop: Removes the top element from the stack.
- Peek: Displays the top element without removing it.
- Display: Shows all stack elements from top to bottom.
- Overflow: Occurs when stack is full.
- Underflow: Occurs when stack is empty.
This is a basic and important data structure implementation in C.
π§Ύ Sample Output:
1. Push 2. Pop 3. Peek 4. Display 5. Exit Enter your choice: 1 Enter data: 10 10 added successfully to stack Enter your choice: 1 Enter data: 20 20 added successfully to stack Enter your choice: 4 Stack elements are: 20 10
π Keywords:
stack in C using array, push pop peek display, data structures C, LIFO stack implementation, stack program C
π Hashtags:
#CProgramming #StackInC #DataStructures #PushPop #CodingBasics #1printf
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment