Stack using CPP Array

11/10/2011 code-examplecpp

# Summary

A stack is an order of list in which all insertion and deletion are made at one end.

The below is the code representing demonstration of working of stack by using push() and pop() functions for entering and removing elements from stack respectively.

# Code

#include "stdio.h"
#include "conio.h"

void push();
void pop();
void display();
int a[6],top=0;

void main()
{
	int i,ch;
	clrscr();
	printf("Enter the following to do the operation:=> \n");
	printf("1. Create\n2. Push\n3. Pop\n4. Display\n5. Exit");
	do
	{
		printf("Enter your choice:=> ");
		scanf("%d",&ch);
		switch(ch)
		{
			case 1:
				printf("New Stack is Created");
				top = 0;
				break;
			case 2:
				push();
				break;
			case 3:
				pop();
				break;
			case 4:
				display();
				break;
			case 5:
				i = 1;
				break;
			default:
				printf("Wrong Choice Entered");
		}
	}while(i!=1);
	getch();
}

// Function to push values / elements in stack

void push()
{
	int n;
	if(top>5)
	{
		printf("Stack is Full");
	}
	else
	{
		printf("Enter the value:=> ");
		scanf("%d",&n);
		a[top] = n;
		top++;
	}
}

// Function to pop out the last entered element

void pop()
{
	if(top == 0)
	{
		printf("Stack is empty");
	}
	else
	{
		top--;
		printf("%d was poped out from stack",a[top]);
	}
}

// Function to display the stack

void display()
{
	int i;
	if(top == 0)
	{
		printf("Stack is empty");
	}
	else
	{
		printf("Displaying the contents of Stack...");
		for(i=top-1;i>=0;i--)
		{
			printf("%d",a[i]);
		}
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94