Completely Solved C, C++ Programs Assignment.




C program to implement a stack using an array

Filed Under: ,

Welcome to mycomputerscience.net! your source for free data structures online course,data structure final exam,computer data structures and interactive data structure visualizations,array implementation of stack.
Array implementation of Stack When an array is used to implement a stack, the push and pop operations are realized by using the operations available on an array. The limitation of an array implementation is that the stack cannot grow and shrink dynamically as per the requirement.
Program A complete C program to implement a stack using an array.
#include <stdio.h>
#define MAX 10 /* The maximum size of the stack */
#include <stdlib.h>
void push(int stack[], int *top, int value)
{
if(*top < MAX )
{
*top = *top + 1;
stack[*top] = value;
}
else
{
printf("The stack is full can not push a valuen");
exit(0);
}
}
void pop(int stack[], int *top, int * value)
{
if(*top >= 0 )
{
*value = stack[*top];
*top = *top - 1;
}
else
{
printf("The stack is empty can not pop a valuen");
exit(0);
}
}
void main()
{
int stack[MAX];
int top = -1;
int n,value;
do
{
do
{
printf("Enter the element to be pushedn");
scanf("%d",&value);
push(stack,&top,value);
printf("Enter 1 to continuen");
scanf("%d",&n);
} while(n == 1);
printf("Enter 1 to pop an elementn");
scanf("%d",&n);
while( n == 1)
{
pop(stack,&top,&value);
printf("The value poped is %dn",value);
printf("Enter 1 to pop an elementn");
scanf("%d",&n);
}
printf("Enter 1 to continuen");
scanf("%d",&n);
} while(n == 1);
}
Output:
Enter the element to be pushed
10
Enter 1 to continue
1
Enter the element to be pushed
20
Enter 1 to continue
0
Enter 1 to pop an element
1
The value popped is 20
Enter 1 to pop an element
0
Enter 1 to continue
1
Enter the element to be pushed
40
Enter 1 to continue
1
Enter the element to be pushed
50
Enter 1 to continue
0
Enter 1 to pop an element
1
The value popped is 50
Enter 1 to pop an element
1
The value popped is 40 Enter 1 to pop an element
1
The value popped is 10 Enter 1 to pop an element
0
Enter 1 to continue
0
Back to main directory:  Data Structure 


Get Free Programming Tutorials and Solved assignments