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

LAB TASK 4 - Array Based Stack Implementation

1) The document describes how to implement a stack using an array in C++. A stack follows LIFO (Last In First Out) principles and supports push(), pop(), and display() operations. 2) It provides code examples of these stack functions as well as an application that allows the user to push and pop values from the stack. 3) The document lists several applications of stacks including undo-redo features, web browser navigation, converting infix to postfix notation, and solving algorithms like towers of Hanoi. It provides exercises to test stack functions and compare opening/closing brackets in an expression using a stack.

Uploaded by

Mohsin Majeed
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)
143 views

LAB TASK 4 - Array Based Stack Implementation

1) The document describes how to implement a stack using an array in C++. A stack follows LIFO (Last In First Out) principles and supports push(), pop(), and display() operations. 2) It provides code examples of these stack functions as well as an application that allows the user to push and pop values from the stack. 3) The document lists several applications of stacks including undo-redo features, web browser navigation, converting infix to postfix notation, and solving algorithms like towers of Hanoi. It provides exercises to test stack functions and compare opening/closing brackets in an expression using a stack.

Uploaded by

Mohsin Majeed
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
You are on page 1/ 10

LAB TASK 4 – Array based Stack implementation

Name / Group ID: ________________________ Reg. No: ___________________

Class / Section: __________________________ Date: _____________________

Time Required : 3 hrs


Programming Language : C++
Software Required : Dev -C++
Hardware Required : Computer System

Stack ADT
A Stack is an Abstract Data Type (ADT) used for storing the elements. The elements are stored
based on the principle of LIFO (Last In, First Out). In stack insertion and deletion of elements
take place at the same end (Top). The last element inserted will be the first to be retrieved.
• This end is called Top
• The other end is called Bottom

Stack supports the following methods:

A stack is an abstract data structure that contains a collection of elements. Stack implements
the LIFO mechanism i.e. the element that is pushed at the end is popped out first. Some of the
principle operations in the stack are −

 Push - This adds a data value to the top of the stack. The push() function takes
argument val i.e. value to be pushed into the stack. If a top is greater than or equal to
n, there is no space in a stack and overflow is printed. Otherwise, val is pushed into
the stack.
Code:

void push(int val) {

if(top>=n-1)

cout<<"Stack Overflow"<<endl;

else {

top++;

stack[top]=val;

 Pop - This removes the data value on top of the stack. The pop() function pops the
topmost value of the stack, if there is any value. If the stack is empty then underflow
is printed.

void pop() {

if(top<=-1)

cout<<"Stack Underflow"<<endl;

else {

cout<<"The popped element is "<< stack[top] <<endl;

top--;

Stack Implementation:
// C++ program to implement basic stack operations
#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=3);
return 0;
}

Applications of stack:
• Balancing of symbols
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop.
• Forward and backward feature in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem,
histogram problem.
• Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen
problem and sudoku solver
• In Graph Algorithms like Topological Sorting and Strongly Connected Components
EXERCICES:
Exercise 1: Display ( ) Function test in main function (2)
Write this function to display the elements of stack e.g.
void display( )
{

#include<iostream>

using namespace std;

void display()

int top=-1;

int stack[100];

if(top>=0)

} {

cout<<"Stack elements are:";

for(int i=top; i>=0; i--)

cout<<stack[i]<<" ";

cout<<endl;

else

cout<<"Stack is empty";

int main()

display();

}
Exercise 2: Implement using stacks. (3)
Write a program using stack operations, which accepts a non-negative base 10 integer as a
parameter, and display binary representation of number.
Description: To convert a number from decimal to binary, you simply divide by two and push
reminder to stack until quotient is reached to zero, then use pop operation to display the
following computation.
35/2 = 1
17/2 = 1
8/2 = 0
4/2 = 0
2/2 = 0
#include<iostream>
1
#include<stack>
If you examine the remainders from the last division to the first one, writing them down as
younamespace
using go, you will
std;get the following sequence: 100011. i.e. (100011)2=(35)10

void dec_to_bin(int number) {

stack<int> stk;

while(number > 0) {

int rem = number % 2; //take remainder

number = number / 2;

stk.push(rem);

while(!stk.empty()) {

int item;

item = stk.top();

stk.pop();

cout << item;

Int main() {

int num;

cout << "Enter a number: ";

cin >> num;

dec_to_bin(num);

}
Exercise 3: (5)
Write a program to compare opening and closing brackets in expression. This program takes an
expression in the form of string and scan it character by character. Finally the output of the
program is the valid or invalid expression.
Algorithm: To do this comparison a stack ADT can be used to keep track of the scope delimiters
encountered while scanning the expression.
• Whenever a scope “opener” is encountered, it can be “pushed” onto a stack
• Whenever a scope “ender” is encountered, the stack is examined: – If the stack is “empty”, there
is no matching scope “opener” and the expression is invalid.
– If the stack is not empty, we pop the stack and check if the “popped” item corresponds to the
scope ender
– If match occurs, we continue scanning the expression

• When end of the expression string is reached, the stack must be empty, otherwise one or more
opened scopes have not been closed and the expression is invalid
// CPP program to check for balanced parenthesis.

#include <bits/stdc++.h>

using namespace std;

// function to check if paranthesis are balanced

bool areParanthesisBalanced(string expr)

stack<char> s;

char x;

// Traversing the Expression

for (inti = 0; i<expr.length(); i++)

if (expr[i] == '(' || expr[i] == '['

|| expr[i] == '{')

// Push the element in the stack

s.push(expr[i]);

continue;

// IF current current character is not opening

// bracket, then it must be closing. So stack


// cannot be empty at this point.

if (s.empty())

return false;

switch (expr[i]) {

case ')':

// Store the top element in a

x = s.top();

s.pop();

if (x == '{' || x == '[')

return false;

break;

case '}':

// Store the top element in b

x = s.top();

s.pop();

if (x == '(' || x == '[')

return false;

break;

case ']':

// Store the top element in c

x = s.top();

s.pop();
if (x == '(' || x == '{')

return false;

break;

// Check Empty Stack

return (s.empty());

// Driver code

intmain()

string expr = "{()}[]";

// Function call

if (areParanthesisBalanced(expr))

cout<< "Balanced";

else

cout<< "Not Balanced";

return 0;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy