Write a program in C for stack using array implementation.
Algorithm :
Step1:Define a array which stores stack elements..
Step 2: The operations on the stack are
a)PUSH data into the stack
b)POP data out of stack
Step 3: PUSH DATA INTO STACK
3a.Enter the data to be inserted into stack.
3b.If TOP is NULLthe input data is the first node in stack. the link of the node is NULL.TOP points to that node.
3c.If TOP is NOT NULL the link of TOP points to the new node.TOP points to that node.
Step 4: POP DATA FROM STACK
4a.If TOP is NULL the stack is empty
4b.If TOP is NOT NULL the link of TOP is the current TOP. the pervious TOP is popped from stack.
Step 5. The stack represented by linked list is traversed to display its content.
Implementation of the above program:
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int stack[SIZE],top=-1;
void push();
void pop();
void display();
void main()
{
int choice;
int isempty();
int length();
clrscr();
while(1)
{
printf(“\n 1.Push”);
printf(“\n 2. POP”);
printf(“\n 3.Display”);
printf(“\n 4. Length ”);
printf(“\n 5.Quit”);
printf(“\n Enter the choice:”);
scanf(“\n %d”,&choice);
switch(choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: printf(“\n No. of elements in the stack is %d”,length());
break;
case 5: exit(0);
break;
default: printf(“\n Invalid choice”);
}
}
}
void push()
{
int n;
if(top==SIZE-1)
printf(“\n Stack is full”);
else
{
printf(“\nEnter the no.”);
scanf(“%d”,&n);
top++;
stack[top]=n;
}
}
void pop()
{
int n;
if(isempty())
{
printf(“\nStack is empty”);
top=-1;
}
else
{
n=stack[top];
printf(“\n %d is popped from the stack \n”,n);
--top;
}
}
void display()
{
int i,temp=top;
if(isempty())
{
printf(“\n Stack Empty”);
return;
}
printf(“\n Elements in the stack:”);
for(i=temp;i>=0;i--)
printf(“%d \n”,stack[i]);
}
int isempty()
{
return (top==-1);
}
int length()
{
return (top+1);
}
The program output is tested on www.jdoodle.com
Output:
1.Push
2. POP
3.Display
4. Length
5.Quit
Enter the choice: 1
Enter the no. 10
1.Push
2. POP
3.Display
4. Length
5.Quit
Enter the choice: 1
Enter the no. 20
1.Push
2. POP
3.Display
4. Length
5.Quit
Enter the choice: 1
Enter the no. 30
1.Push
2. POP
3.Display
4. Length
5.Quit
Enter the choice: 1
Enter the no. 40
1.Push
2. POP
3.Display
4. Length
5.Quit
Enter the choice: 3
Elements in the stack:
40
30
20
10
1.Push
2. POP
3.Display
4. Length
5.Quit
Enter the choice: 2
40 is popped from the stack
1.Push
2. POP
3.Display
4. Length
5.Quit
Enter the choice: 4
Number of elements in the stack is 3
1.Push
2. POP
3.Display
4. Length
5.Quit
Enter the choice: 5
Thanks
Mukesh Rajput
Post A Comment:
0 comments: