0% found this document useful (0 votes)
17 views14 pages

C++ Array-Based Stack Implementation

The document describes implementing a stack using arrays in C++. It discusses implementing stacks using static and dynamic arrays as well as class templates. It provides code examples for pushing and popping elements from a static array-based stack implementation and functions for checking if the stack is empty or full.

Uploaded by

Asim Shareef
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views14 pages

C++ Array-Based Stack Implementation

The document describes implementing a stack using arrays in C++. It discusses implementing stacks using static and dynamic arrays as well as class templates. It provides code examples for pushing and popping elements from a static array-based stack implementation and functions for checking if the stack is empty or full.

Uploaded by

Asim Shareef
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Department of Computer Science, Faculty of Computing

International Islamic University, Islamabad

Lab Manual for Data Structures


Lab-5
Array based Stack implementation
Lab 5: Array based Stack implementation

Table of Contents
1. Introduction............................................................................................................................................................3
1.1 Stack implementation as a static array...................................................................................................................3
1.2 Stack implementation as a dynamic array.............................................................................................................3
1.3 Stack as a class template........................................................................................................................................3
1.4Relevant Lecture Readings..........................................................................................................................................3
2. Activity Time boxing.............................................................................................................................................4
3. Objectives of the experiment.................................................................................................................................4
4. Concept Map..........................................................................................................................................................4
4.1 stack class using a static array.....................................................................................................................................4
4.2Stacks using dynamic arrays........................................................................................................................................6
4.3Stack using a class template.........................................................................................................................................8
6. Procedure& Tools................................................................................................................................................................9
6.1 Tools............................................................................................................................................................................9
6.2 Walk through Tasks [Expected time = 20mins].................................................................................................9
7. Practice Tasks....................................................................................................................................................................11
7.1 Practice Task 1 [Expected time = 15mins]......................................................................................................11
7.2 Practice Task 2 [Expected time = 20mins]....................................................................11
7.4Out comes...................................................................................................................................................................12
7.5Testing........................................................................................................................................................................13
[Link] Task (Unseen) [Expected time = 60mins]..................................................................................................13
9. Evaluation criteria.............................................................................................................................................................14
10. Further Readings.............................................................................................................................................................14
10.1 Web sites related to C++ tutorials related to stacks................................................................................................14
10.2 Web sites containing supporting material...............................................................................................................14

Department of Computer Science Page 2


IIUI, Islamabad
Lab 5: Array based Stack implementation

Lab 5: Array based Stack implementation with


template class

1. Introduction
Objective of this lab is to introduce the implementation of stack in C++ and further introduce
concept of class templates and defining a stack as a class template or generic class. A stack allows last in
first out (LIFO) operations. We can place a new element at top of stack and we may remove an element
from top of stack. Stacks can be implemented using static as well as dynamic arrays. Further we may
implement a stack as a generic class/class template.

1.1 Stack implementation as a static array

A stack can be implemented using a static array in C++. We need to define an array with a
maximum size and a variable of integer type normally called “top” for such stack. Stack is initially set to
empty when program is executed, so at start of program top is set to -1 which represents an empty stack.
There are two operations associated with a stack; push operation—used to add an element at top of stack
and pop operation – to remove an element from top of stack. When push operation is performed we need
to check that whether stack exceeds its maximum size or not, this is called stack overflow condition
check. When pop operation is performed we need to test that whether stack is empty or not, this is called
stack underflow condition check.

1.2 Stack implementation as a dynamic array

When maximum size of stack is to be decided at program execution time, then we need a dynamic
array to represent the stack. Size of such array is specified at program execution time, a pointer is defined
in program which points to an array dynamically created. Even the stack with dynamic array is
implemented for stack overflow and underflow conditions in push and pop operations respectively.

1.3 Stack as a class template


A class template is a generic class which is defined as a template, from which multiple different
classes can be generated. If we need to design a stack which can be used for integer, float, string and other
primitive data types, we can define this stack as a class template. From this class template we may
generate different stack classes which can be used to represent integers, floats, strings and other primitive
data types as well for user defined data types.
1.4Relevant Lecture Readings

a) Revise Lecture No. 7 and 8 available at \\fs\lectures$ in instructor’s folder.


b) From books: C++ Data Structures by Nell Dale (Page 196-225) and Data structures using
C++ by D. S. Malik (Page 405-411).

Department of Computer Science Page 3


IIUI, Islamabad
Lab 5: Array based Stack implementation

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Design Evaluation 20mins 20mins
6.2 Walk through tasks 20mins 20mins
7 Practice tasks 15 mins for task 1, 20 mins for 70mins
task 2 and 35 mins for task 3
9 Evaluation Task 60mins for all assigned tasks 60mins

3. Objectives of the experiment


 To get knowledge of implementing stacks using static arrays in C++.
 To get knowledge of implementing stacks using dynamic arrays in C++.
 To get knowledge of implementing stacks as stack class template in C++.

4. Concept Map
This concept map will help students to understand the main concepts of topic covered in lab.
4.1 stack class using a static array
Following is an implementation of stack using static array in C++.

#include <iostream>
using namespace std;

const int STACKSIZE = 10;


class stack{
private:
int arr[STACKSIZE];
int tos;
public:
stack();
void push(int x);
int pop();
bool empty();
bool full();
int size();
void display();
};

stack::stack()
{
tos = -1;
}
Department of Computer Science Page 4
IIUI, Islamabad
Lab 5: Array based Stack implementation

void stack::push(int x)
{
if(!full())
arr[++tos] = x;
else
cout<< "Stack is full, Cannot push " << x <<endl;
}

int stack::pop()
{
if(!empty())
return arr[tos--];
else
cout<< "Stack is empty, cannot pop" <<endl;
return -1;
}

bool stack::empty()
{
if(tos == -1)
return true;
else
return false;
}

bool stack::full()
{
if(tos+1 == STACKSIZE)
return true;
else
return false;
}

int stack::size()
{
return tos;
}

void stack::display()
{
if(tos == -1)
{
cout<< "No elements to display" <<endl;
return;
}
for(int i=0;i < STACKSIZE; i++)
Department of Computer Science Page 5
IIUI, Islamabad
Lab 5: Array based Stack implementation

cout<<arr[i] << " ";


cout<<endl;
}

int main()
{
stackmystack;
cout<<[Link]() <<endl;
[Link](1);
if([Link]())
cout<< "stack is full" <<endl;
[Link]();
if([Link]())
cout<< "stack is empty" <<endl;
}

Following figure 1 represents the functionality of pop and push operations on a stack implemented
using a static array.

Figure 1: push and pop operations on a stack

4.2Stacks using dynamic arrays


A stack which is implemented using an array whose size is determined at program execution time
is implemented using a dynamic array.
A destructor is a special member function in a class that is called when an object of that class goes out of
scope or is explicitly deleted. It is responsible for cleaning up any resources or performing any necessary
cleanup operations associated with the object. The code within the destructor will be executed when an
instance of the Stack class is destroyed.

For the array implementation, we need to keep track of (at least) the array contents and a top
index. Definition of stack class will be as:

class Stack{
public:
Stack(int stack_size);
Department of Computer Science Page 6
IIUI, Islamabad
Lab 5: Array based Stack implementation

~Stack();
void push(int x);
int pop();
bool isEmpty();
bool isFull();

private:
char *contents;
int top;
};

Stack::Stack(int stack_size)
{

contents = new char[stack_size];

if (contents == NULL) {
cout<< "Insufficient memory to initialize stack.\n";
exit(1);
}

maxSize = stack_size;
top = -1;
}

Stack::~Stack()
{
delete [] contents;

contents = NULL;
maxSize = 0;
top = -1;
}

bool Stack::isEmpty() const


{
return top < 0;
}

void Stack::push(char element)


{
if (isFull()) {
cout<< "Can't push element on stack: stack is full.\n";
exit(1);
}

contents[++top] = element;
Department of Computer Science Page 7
IIUI, Islamabad
Lab 5: Array based Stack implementation

char Stack::pop()
{
if(!isEmpty())
return contents[--top];
else
cout<< "Stack is empty, cannot pop" <<endl;
return -1;
}
4.3Stack using a class template
A stack using a class template provides a generic implementation of stack which provides facility
to use stack with many primitive and user defined data types. Creating a stack using a class template in C+
+ provides a way to create a generic stack that can store elements of any data type. Using templates allows
you to write code that is independent of the specific type of data that the stack will hold, providing
flexibility and code reusability.

template <class Typ, intMaxStack>


class Stack {
int EmptyStack;
Typ items[MaxStack];
int top;
public:
Stack();
~Stack();
void push(Typ);
Typ pop();
int empty();
int full();
};

Template < class Typ, intMaxStack>


Stack <Typ, MaxStack>::Stack() {
EmptyStack = -1;
top = EmptyStack;
}

template< class Typ, intMaxStack>


Stack<Typ, MaxStack>::~Stack()
{ delete[] items; }

template< class Typ, intMaxStack>


void Stack<Typ, MaxStack>::push(Typ c)
{ items[ ++top ] = c; }

template< class Typ, intMaxStack>


Typ Stack<Typ, MaxStack>::pop()
Department of Computer Science Page 8
IIUI, Islamabad
Lab 5: Array based Stack implementation

{ return items[ top-- ]; }

template< class Typ, intMaxStack>


int Stack<Typ, MaxStack>::full()
{ return top + 1 == MaxStack; }

template< class Typ, intMaxStack>


int Stack<Typ, MaxStack>::empty()
{ return top == EmptyStack; }

int main() {
Stack<char, 10> s; // 10 chars
Char ch;
while ((ch = [Link]()) != '\n')
if (![Link]()) [Link](ch);
while (![Link]())
cout<<[Link]();
cout<<endl;
Stack<double, 4> ds; // 4 doubles
double d[] =
{1.0, 3.0, 5.0, 7.0, 9.0, 0.0};
int i = 0;
while (d[i] != 0.0 && ![Link]())
if (![Link]()) [Link](d[i++]);
while (![Link]())
cout<<[Link]() << " ";
cout<<endl;
return 0;
}
6. Procedure& Tools
This section provides information about tools and programming procedures used for the lab.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
6.2 Walk through Tasks [Expected time = 20mins]
We will discuss the demonstration of stack using static array in Microsoft Visual Studio 2017. You
are required to open an empty Win32 console application. You have already knowledge of creating a
console application in Microsoft Visual Studio 2017 in your courses: computer programming and object
oriented programming, which you have previously studied.

Following figure 2 represents the implementation of class in editor window.

Department of Computer Science Page 9


IIUI, Islamabad
Lab 5: Array based Stack implementation

Figure 2: Stack definition using static array in Microsoft Visual Studio 2017.

Figure 3 shows push and pop operations implementation.

Figure 3: Implementation of push and pop operations for stack using static array in Microsoft Visual Studio
2017

Figure 4 represents the output of this program when executed.

Department of Computer Science Page 10


IIUI, Islamabad
Lab 5: Array based Stack implementation

Figure 4: Output window displaying values from stack in Microsoft Visual Studio 2017

7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed in lab
session. Design solutions of problems discussed in each task and placesolution code in a folder specified
by your lab instructor.

Lab instructors are guided to help students learn how ACM problems work and provide students
with certain practice/home tasks on the pattern of ACM Problems.

7.1 Practice Task 1 [Expected time =


15mins]
Write a program to implement a Stack using dynamic array of Character values. Implement the following
functions in Stack with necessary checks: use Class name Stack and add all stack functions as member
functions.
a) Insert value in Stack (PUSH)
b) Delete value from Stack (POP)
c) Display the Stack.

7.2 Practice Task 2 [Expected time =


20mins]

Create a Stack of integer using arrays. Give the following menu to the user and then implement the given
operations:

Press 1 to PUSH a value in Stack

Press 2 to POP a value from Stack

Press 3 to display the Stack


Department of Computer Science Page 11
IIUI, Islamabad
Lab 5: Array based Stack implementation

Press 4 to Show the next greater element in the Stack.

Sample Input:

Stack

3 2 6 7 8 13

Press 1 to PUSH a value in Stack

Press 2 to POP a value from Stack

Press 3 to display the Stack

Press 4 to Show the next greater element in the Stack.

Sample Output:

The next greater elements for the given Stack are:

36

26

67

78

813

13-1

7.4Out comes
After completing this lab, student will be able to understand and develop programs related stacks using
static and dynamic arrays and using stack as class template in C++ using Microsoft Visual Studio 2017
environment.

7.5Testing

Test Cases for Practice Task-1


Department of Computer Science Page 12
IIUI, Islamabad
Lab 5: Array based Stack implementation

Sample Sample
Inputs-1 Outputs-1
Push elements for stack:
2
3
4
5
8
Enter number of elements to be popped from
stack1: 3
Elements of stack popped:
8
5
4

Test Cases for Practice Task-3 a

Sample Sample
Inputs-1 Outputs-1
Enter expression:
{{{
Can't be made balanced using reversals
Enter expression:
{{{{
2
Enter expression:
{{{{}}
1

Test Cases for Practice Task-3 b

Sample Sample
Inputs-1 Outputs-1
Input : abaabcdabf
new sequence is:
acdab

[Link] Task (Unseen) [Expected


time = 60mins]

The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).

Table 2: Evaluation of the Lab


Department of Computer Science Page 13
IIUI, Islamabad
Lab 5: Array based Stack implementation

Sr. No. Task No Description Marks


1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7,8 Practice tasks and Testing 35
4 8.1 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

10. Further Readings


10.1 Web sites related to C++ tutorials related to stacks
1. [Link]
2. [Link]
10.2 Web sites containing supporting material

1. [Link]

Department of Computer Science Page 14


IIUI, Islamabad

Common questions

Powered by AI

Templates in a stack implementation promote code reusability and flexibility by allowing the same code to handle different data types without modification. By defining a stack as a class template, the same implementation can be used for multiple data types, such as integers, floats, or custom objects, thereby avoiding code duplication and enhancing maintainability . This approach centralizes changes and improvements across all types the stack can handle, streamlining updates and bug fixes, and allows for applying uniform logic across various data instances .

Creating a stack with a dynamic array differs from a static array in terms of memory allocation timing and flexibility. A static array allocates a fixed memory size during compile time, limiting flexibility and potentially wasting space if the entire allocated memory isn't used . In contrast, a dynamic array allocates memory at runtime based on the required size, allowing more efficient memory usage and the ability to set stack size according to actual needs, reducing waste and allowing more flexible scaling .

The main differences between implementing a stack using a static array and a dynamic array in C++ are in their flexibility and memory management. A static array-based stack has a fixed size determined at compile time, and the 'top' index is initialized at -1 to indicate an empty stack . This approach requires a check for stack overflow and underflow during push and pop operations, respectively . In contrast, a dynamic array allows the size of the stack to be decided at runtime, offering more flexibility. Dynamic arrays use pointers to allocate memory during program execution, which can help to manage resources more efficiently, though they too require checks for stack overflow and underflow during operations .

A class template enhances the implementation of stacks in C++ by allowing the stack to be a generic class, capable of handling different data types, such as integers, floats, strings, and user-defined types . This is achieved by defining the stack as a template class from which multiple specific stack classes can be generated for various data types, thus providing flexibility and code reusability . Templates enable a single codebase to operate with any data type, enhancing the versatility of the implementation .

Activity time boxing in lab sessions helps enhance efficiency by structuring the time allocated for each task, ensuring focus and minimizing time wastage. By setting specific durations for tasks like design evaluation, walkthroughs, and practice, students can manage their time effectively, prioritize their workload, and maintain concentration, thereby improving task completion within the allotted time . This approach helps in achieving learning objectives within the constrained timeframe of a lab session .

Setting the 'top' index to -1 in a stack implemented using a static array signifies that the stack is initially empty . This index is used to manage stack operations by serving as a pointer to the current top of the stack. When the stack is empty, 'top' being -1 prevents pop operations until a push operation increments it, thus ensuring appropriate conditions for both operations to function correctly .

Stack underflow occurs when there's an attempt to pop an element from an empty stack, and stack overflow occurs when adding an element to a full stack. If not properly handled, these conditions could lead to erroneous program execution by either trying to access unallocated memory or overwriting existing data, respectively . This would not only cause logical errors and unexpected behaviors in a program but might also compromise the program's integrity, potentially leading to crashes or security vulnerabilities due to mishandled memory access .

During push operations in a stack using static arrays, it is crucial to check for the stack overflow condition, which occurs when attempting to add an element to a full stack . Similarly, during pop operations, the stack underflow condition must be checked, which occurs when attempting to remove an element from an empty stack . These checks ensure that the stack operations are safely managed and errors are prevented during runtime.

The purpose of the destructor in a stack implemented with dynamic arrays in C++ is to handle resource cleanup when an object of the stack class goes out of scope or is explicitly deleted. The destructor deallocates the dynamically allocated memory for the array, ensuring that memory leaks are prevented and resources are freed correctly . It sets pointers to zero or NULL and resets indices, thus maintaining good memory management practices and safeguarding against potential errors from accessing freed memory .

Typical operations implemented in a stack class template in C++ include push, pop, full, and empty operations. The push operation adds an element to the top of the stack, while the pop operation removes the top element. The full operation checks whether the stack has reached its maximum allowable capacity, and the empty operation verifies if the stack is devoid of elements . These operations provide the basic functionality for maintaining and manipulating stack data efficiently .

You might also like