C++ Program to Implement Stack using array
Last Updated :
24 May, 2024
Stack is the fundamental data structure that can operates the under the Last In, First Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed. Implementing the stack using the array is one of the most straightforward methods in the terms of the both understanding and coding.
Implementation of Stack in C++
The stack can be implemented using the array organizes its the elements in contiguous memory locations. We can enclose this array in a class as a member and encapsulate the methods and data related to the stack in that class for easy and organized access.
class Stack {
public:
int stackArr[size];
int stackSize;
// constructors and methods
};
Basic Operations on a Stack in C++
1. Push operation
This operation can be used to adds the element to the top of the stack.
Algorithm
1. Check if stack is full. If it is indicate the overflow condition.
2. Increment the top index.
3. Place the new element at top position in the array.
2. Pop Operation
This operation can be used to removes and returns the top element of the stack.
Algorithm
1. Check if stack is empty. If it is indicates the underflow condition.
2. Retrieve the element at top index.
3. Decrement the top index.
4. Return the retrieved element.
3. Peek Operation
The operation can be used to returns the top element without the removing it from the stack.
Algorithm
1. Check if stack is empty. If it is return an error or special value indicating the stack is empty.
2. Return the element at top index without the modifying the top.
4. IsEmpty operation
This operation can checks if the stack contains no elements of the stack.
Algorithm
1. Return the true if the top index is -1 then otherwise return false.
4. IsFull Operation
This operation can checks if the stack has been reached its the maximum capacity of the stack.
Algorithm
1. Return the true if top index is equal to maximum index otherwise return false.
C++ Program to Implement Stack using array
C++
// Include necessary libraries
#include <iostream>
using namespace std;
// Define Stack class
class Stack {
// Pointer to an array that stores elements of the stack
int* arr;
// Index of the top element in the stack
int top;
// Maximum size of the stack
int capacity;
public:
// Constructor to initialize the stack
Stack(int size)
{
// Allocate memory for the stack
arr = new int[size];
// Set the maximum size of the stack
capacity = size;
// Initialize the top of the stack as -1 indicating
// the stack is empty
top = -1;
}
// Destructor to deallocate memory
~Stack() { delete[] arr; }
// Function to add an element x in the stack
void push(int x)
{
// Check if the stack is full
if (isFull()) {
cout << "Overflow\n";
return;
}
cout << "Pushing " << x << "\n";
// Add element and increment top
arr[++top] = x;
}
// Function to remove an element from the stack
int pop()
{
// Check if the stack is empty
if (isEmpty()) {
cout << "Underflow\n";
return -1;
}
// Remove element and decrement top
return arr[top--];
}
// Function to return the top element of the stack
int peek()
{
if (!isEmpty())
return arr[top];
else
return -1;
}
// Function to return if the stack is empty
bool isEmpty() { return top == -1; }
// Function to return if the stack is full
bool isFull() { return top == capacity - 1; }
};
// Main function
int main()
{
// Create a stack of size 3
Stack stack(3);
// Push elements into the stack
stack.push(10);
stack.push(20);
stack.push(30);
// Print the top element of the stack
cout << "The top element is " << stack.peek() << endl;
// Pop an element from the stack and print it
cout << "Popping " << stack.pop() << endl;
// Print the top element of the stack
cout << "The top element is " << stack.peek() << endl;
// Pop all elements from the stack
stack.pop();
stack.pop();
// Check if the stack is empty and print the result
if (stack.isEmpty()) {
cout << "The stack is empty" << endl;
}
else {
cout << "The stack is not empty" << endl;
}
return 0;
}
OutputPushing 10
Pushing 20
Pushing 30
The top element is 30
Popping 30
The top element is 20
The stack is empty
Time and Space Complexity
- Time complexity: O(1)
- Space complexity: O(n), where n is number of elements in array
Applications of the Stack
- It can applies the Function Call Management.
- It can be applies on the Expression Evaluation to convert the infix expressions to postfix.
- It can be used in the Backtracking algorithms.
- It can be applies on the complier use stacks for the syntax checking and parsing.
- It can applies on the Undo Mechanisms like text editors.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read