ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Data structure tutorial 1: Introduction to Stack Data structure and Implementation using arrays

prodevelopertutorial May 19, 2019

What is a Stack?

Stack is a special type of data structure where in the elements are entered from one end and are deleted from same end.

Stack is also called as Last In First Out data structure [LIFO]. Because the elements that are entered Last will be removed at First.

Below is the pictorial example of Stack:

stack

Below are the various operations that can be performed on a Stack:

  1. Push: Insert element to stack
  2. Pop: Remove element from stack
  3. Overflow: Check if stack is full
  4. Under flow: Check if stack is empty.
  5. Display: Show the contents of the stack.

Below are the important functions that we will be using:

1. push ():

We use push operation to insert an element into the stack. Here before pushing an element into the stack, we should make sure that the stack is having enough space for that operation.

That can be done by checking the present stack size and maximum stack size. If the present stack size is less than maximum stack size, then we will insert the element and increment the present stack size by one.

Below is the pictorial example of push operation:

Here we are inserting 10, 20, 30, 40 into the stack.

 

stacks

2. pop ():

We use pop to remove/delete an element from the stack. Before removing an element, we need to check if the stack has some elements.

Removing elements from a stack having no elements will result in Stack Underflow.

Below is the pictorial example of pop operation:

Here we are removing 40, 30, 20, 10 from the stack.

stack

3. display ()

Display method is used to display all the elements from the stack. If there are no elements, then appropriate error message should be displayed.

Stacks can be implemented in 2 ways.

  1. Using arrays
  2. Using Linked List

In this tutorial we shall see how to implement stack using arrays. In the next tutorial we shall see how to implement stacks using linked list.

C program to implement stack using arrays:

#include<stdio.h>
#include<stdlib.h>

#define STACK_SIZE	5

int top_index = 0; /* Variable to hold top index */
int stack_items[10]; /* Array to hold stack items */
int item = 0; /* Variable to hold the value to be inserted into stack*/

//function to check if stack is full
int IsFull()
{
	return (top_index == STACK_SIZE - 1);
}

//function to insert an element in stack
void push()
{
	if (IsFull())
	{
		printf("Stack is full. Cannot insert more elements \n");
		return;
	}

	top_index = top_index + 1;
	stack_items[top_index] = item;
}

//function to check if the stack is empty
int IsEmpty()
{
	return top_index == -1;
}

//function to delete an element in stack
int pop ()
{
	if (IsEmpty())
		{
				return -1;
		}

	return stack_items[top_index --];
}

// function to display elements in the stack
void display()
{
	if(top_index == -1)
	{
		printf("Stack is empty\n");
		return;
	}

	printf("The contents of the stack are:\n");

	for (int i = 0; i <= top_index; ++i)
	{
		printf("%d\n", stack_items[i]);
	}
	return;
}


int main()
{
	int deleted_item = 0;
	int choice = 0;

	top_index = -1;

	for( ; ; )
	{
		printf("1. Push \n2. Pop \n3. Display \n4. Exit\n");

		scanf("%d", &choice);

		switch(choice)
		{
			case 1:
				printf("\nEnter the item to be inserted\n");
				scanf("%d", &item);

				push();
			break;

			case 2:
				deleted_item = pop();

				if(deleted_item == -1)
					{
						printf("Stack is empty\n");
					}
					else
					{
						printf("Deleted Item = %d\n",deleted_item );
					}
			break;

			case 3:
				display();
				break;

			default:
				exit(0);
		}
	}

	return 0;
}

Output:

1. Push
2. Pop
3. Display
4. Exit
3
Stack is empty

1. Push
2. Pop
3. Display
4. Exit
1

Enter the item to be inserted
2

1. Push
2. Pop
3. Display
4. Exit
1

Enter the item to be inserted
3
1. Push
2. Pop
3. Display
4. Exit
3

The contents of the stack are:
2
3

1. Push
2. Pop
3. Display
4. Exit
2

Deleted Item = 3

1. Push
2. Pop
3. Display
4. Exit
3
The contents of the stack are:
2

1. Push
2. Pop
3. Display
4. Exit
4

Further Reading:

AJ’s definitive guide for DS and Algorithms. Click here to study the complete list of algorithm and data structure tutorial. 85+ chapters to study from.

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT