0% found this document useful (0 votes)
171 views

Stack Program in C

This document discusses implementing a stack in C programming language. It includes functions to check if the stack is empty or full, peek at the top element, and push or pop elements onto and off of the stack. The main function demonstrates pushing multiple elements onto the stack, peeking at the top, popping all elements off and printing them, and checking if the stack is full or empty.

Uploaded by

CM-111 jeevin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views

Stack Program in C

This document discusses implementing a stack in C programming language. It includes functions to check if the stack is empty or full, peek at the top element, and push or pop elements onto and off of the stack. The main function demonstrates pushing multiple elements onto the stack, peeking at the top, popping all elements off and printing them, and checking if the stack is full or empty.

Uploaded by

CM-111 jeevin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

STACK PROGRAM IN C

http://www.tutorialspoint.com/data_structures_algorithms/stack_program_in_c.htm Copyright © tutorialspoint.com

We shall see the stack implementation in C programming language here. You can try the program
by clicking on the Try-it button. To learn the theory aspect of stacks, click on visit previous page.

Implementation in C

#include <stdio.h>

int MAXSIZE = 8;
int stack[8];
int top = -1;

int isempty() {

if(top == -1)
return 1;
else
return 0;
}

int isfull() {

if(top == MAXSIZE)
return 1;
else
return 0;
}

int peek() {
return stack[top];
}

int pop() {
int data;

if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
}else {
printf("Could not retrieve data, Stack is empty.\n");
}
}

int push(int data) {

if(!isfull()) {
top = top + 1;
stack[top] = data;
}else {
printf("Could not insert data, Stack is full.\n");
}
}

int main() {
// push items on to the stack
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);
printf("Element at top of the stack: %d\n" ,peek());
printf("Elements: \n");

// print stack data


while(!isempty()) {
int data = pop();
printf("%d\n",data);
}

printf("Stack full: %s\n" , isfull()?"true":"false");


printf("Stack empty: %s\n" , isempty()?"true":"false");

return 0;
}

Output
Output of the program is as follows −

Element at top of the stack: 15


Elements:
15
12
1
9
5
3
Stack full: false
Stack empty: true

You might also like