You are on page 1of 12

Day 4:

Recursion

Stacks

Queues

Recursion

• It involves a function calling itself.


• It is a programming pattern that is useful in situations when a task can be naturally split into several tasks of the
same kind, but simpler.

Now let’s examine how recursive calls work. For that we’ll look under the hood of functions.

• The information about a function run is stored in its execution context.

• The execution context is an internal data structure that contains details about the execution of a function: where
the control flow is now, the current variables, the value of this (we don’t use it here) and few other internal
details.

• One function call has exactly one execution context associated with it.

• When a function makes a nested call, the following happens:


o The current function is paused.
o The execution context associated with it is remembered in a special data structure called execution
context stack.
o The nested call executes.
o After it ends, the old execution context is retrieved from the stack, and the outer function is resumed
from where it stopped.

Any recursive function can be rewritten into an iterative one. And that’s sometimes required to optimize stuff. But for
many tasks a recursive solution is fast enough and easier to write and support.

Using recursive algorithm, certain problems can be solved quite easily.

Why Stack Overflow error occurs in recursion?

If base case (condition) is not reached or not defined, then stack overflow problem may arise.
Function to calculate sum of all digits using Iteration

int sumDigits(int num)


{
static int sum = 0;
if (num > 0)
{
int value = num;
int i = 1;
do {
int digit = (value % 10);
sum = sum + digit;
value = value / 10;
i++;
} while (value != 0);
}
return sum;
}

Function to calculate sum of all digits using recursion

int sumDigits(int num)


{
static int sum = 0;
if (num > 0)
{
int digit = (num % 10);
sum = sum + digit;
sumDigits(num / 10);
}
else
{
return sum;
}
}
Stack

• Stack is a collection of items.


• It allows access to only one data item: the last item inserted.
• Items are inserted & deleted at one end called ‘Top of the stack’.
• It is a dynamic & constantly changing object.
• All the data items are put on top of the stack and taken off the top
• This structure of accessing is known as Last in First out structure (LIFO)

For example,

A stack can be helpful when you need to temporarily store an element that is going to be used in the immediate steps of
your program. For instance, programming languages usually use a stack structure to pass variables to functions. What they
do is store (or push) the function arguments in the stack and then jump to the function where they remove and retrieve
(or pop) the same number of elements from the stack. That way the size of the stack is dependent of the number of nested
calls of functions. Additionally, after a function has been called and finished what it was doing, it leaves the stack in the
exact same condition as before it has being called! That way any function can operate with the stack ignoring how other
functions operate with it.

stack.h

#define SIZE 5
class CStack
{
private:
int num[SIZE];
int top;
public:
CStack(); //defualt constructor
int push(int);
int pop();
int isEmpty();
int isFull();
void displayItems();
};
stack.cpp

#include "pch.h"
#include <iostream>
#include "stack.h"
using namespace std;

CStack::CStack() {
top = -1;
}

int CStack::isEmpty() {
if (top == -1)
return 1;
else
return 0;
}

int CStack::isFull() {
if (top == (SIZE - 1))
return 1;
else
return 0;
}

int CStack::push(int n) {
//check stack is full or not
if (isFull()) {
return 0;
}
++top;
num[top] = n;
return n;
}

int CStack::pop() {
//to store and print which number is deleted
int value;
//check for empty
if (isEmpty())
return 0;
value = num[top];
--top;
return value;
}

void CStack::displayItems() {

cout << "STACK is: ";


for (int i = (top); i >= 0; i--)
cout << num[i] << " ";
cout << endl;
}
main.cpp

#include "pch.h"
#include <iostream>
#include "stack.h"
using namespace std;

int main()
{
CStack stk;
int choice, n, temp;
do
{
cout << endl;
cout << "0 - Exit." << endl;
cout << "1 - Push Item." << endl;
cout << "2 - Pop Item." << endl;
cout << "3 - Display Items (Print STACK)." << endl;

cout << "Enter your choice: ";


cin >> choice;

switch (choice) {
case 0: break;

case 1:
cout << "Enter item to insert: ";
cin >> n;
temp = stk.push(n);
if (temp == 0)
cout << "STACK is FULL." << endl;
else
cout << temp << " inserted." << endl;
break;

case 2:
temp = stk.pop();
if (temp == 0)
cout << "STACK IS EMPTY." << endl;
else
cout << temp << " is removed (popped)." << endl;
break;

case 3:
stk.displayItems();
break;

default:
cout << "An Invalid choice." << endl;
}
} while (choice != 0);
}
Queue

Queue is a collection of the same type of element. It is a linear list in which insertions can take place at one end of the
list,called rear of the list, and deletions can take place only at other end, called the front of the list.

• Queue is a ordered collection of items.


• Items are deleted at one end called ‘front’ end of the queue.
• Items are inserted at other end called ‘rear’ of the queue.
• The first item inserted is the first to be removed (FIFO).

For example

For GUI (Graphical User Interface) Application, events generated by keyboard,mouse input devices are sent to Application
Message Queue.

Message Pump implementation of Application Fetch message from queue and dispatched for event handling registerd
(subscribed ) in Application.

queue.h

#define MAX 5
class CQueue
{
private:
int front, rear;
int data[MAX];
public:
CQueue() //To Initalize queue
{
front = 0;
rear = -1;
}

int isFull();
int isEmpty();
void insertQueue(int item);
int deleteQueue(int *item);
};
queue.cpp

#include "pch.h"
#include <iostream>
#include "queue.h"
using namespace std;

//To check queue is full or not


int CQueue::isFull()
{
int full = 0;
if (rear == MAX - 1)
full = 1;
return full;
}

//To check queue is empty or not


int CQueue::isEmpty()
{
int empty = 0;
if (front == rear + 1)
empty = 1;
return empty;
}

//Insert Item into queue


void CQueue::insertQueue(int item)
{
if (isFull())
{
cout << "\nQueue OverFlow" << endl;
return;
}
data[++rear] = item;
cout << "\ninserted Value :" << item;
}

//delete item from queue


int CQueue::deleteQueue(int *item)
{
if (isEmpty())
{
cout << "\nQueue Underflow" << endl;
return -1;
}
*item = data[front++];
return 0;
}
main.cpp

#include "pch.h"
#include <iostream>
#include "queue.h"
using namespace std;

int main()
{
int item = 0;

CQueue q = CQueue();

q.insertQueue(10);
q.insertQueue(20);
q.insertQueue(30);
q.insertQueue(40);

if (q.deleteQueue(&item) == 0)
cout << "\nDeleted item : " << item;

if (q.deleteQueue(&item) == 0)
cout << "\nDeleted item : " << item;
if (q.deleteQueue(&item) == 0)
cout << "\nDeleted item : " << item;

if (q.deleteQueue(&item) == 0)
cout << "\nDeleted item : " << item;

if (q.deleteQueue(&item) == 0)
cout << "\nDeleted item : " << item;

cout << endl;


getchar();

return 0;
}
Priority Queue

A Priority queue is used in many computing applications.

For example, many operating systems used a scheduling algorithm where the nexe task executed in the onle with the
shortest execution time or the hightst priority

For another example, consider the problem of sorting a file of data representing persons.

We can use a priority queue to sort the data by :

1. first adding all of the person to a queue.


2. sort data in certain order according to the specified priority
3. remove them in turn from the priority queue (Front element first)

priority.h

#include <iostream>
using namespace std;
#define MAX 5

//Declaration of priority queue


class CPriorityQueue
{
private:
int data[MAX][MAX];
int count;

public:
CPriorityQueue();
void insertWithPriority(int priority, int item);
int GetNext(int *item);
int PeekAtNext(int *item);
};
priority.cpp

#include "pch.h"
#include "priorityqueue.h"

//Initialize priority queue

CPriorityQueue::CPriorityQueue()
{
int i = 0;
count = 0;
//All priority value set to -1
for (i = 0; i < MAX; i++)
{
data[i][1] = -1;
}
}

//Insert item with priority in queue

void CPriorityQueue::insertWithPriority(int priority, int item)


{
int i = 0;
if (count == MAX)
{
cout << "\nPriority Queue is overflow";
return;
}

for (i = 0; i < MAX; i++)


{
if (data[i][1] == -1)
break;
}

data[i][0] = item;
data[i][1] = priority;

count++;
cout << "\nInserted item is : " << item;
}
//Remove & get element with highest priority in queue

int CPriorityQueue::GetNext(int *item)


{
int i = 0, max, pos = 0;

if (count == 0)
{
cout << "\nPriority Queue is underflow";
return -1;
}

max = data[0][1];
for (i = 1; i < MAX; i++)
{
if (max < data[i][1])
{
pos = i;
max = data[i][1];
}
}

*item = data[pos][0];
data[pos][1] = -1;

count--;
return 0;
}

//Get element with highest priority without removing it from queue

int CPriorityQueue::PeekAtNext(int *item)


{
int i = 0, max, pos = 0;
if (count == 0)
{
cout << "\nPriority Queue is underflow";
return -1;
}

max = data[0][1];
for (i = 1; i < MAX; i++)
{
if (max < data[i][1])
{
pos = i;
max = data[i][1];
}
}
*item = data[pos][0];
return 0;
}
main.cpp

#include "pch.h"
#include "priorityqueue.h"
#include <iostream>
int main()
{
int item;
CPriorityQueue q = CPriorityQueue();

q.insertWithPriority(1, 10);
q.insertWithPriority(2, 20);
q.insertWithPriority(3, 30);
q.insertWithPriority(4, 40);
q.insertWithPriority(5, 50);
q.insertWithPriority(6, 60);

if (q.PeekAtNext(&item) == 0)
cout << "\nPeek Item : " << item;

if (q.GetNext(&item) == 0)
cout << "\nItem : " << item;

if (q.PeekAtNext(&item) == 0)
cout << "\nPeek Item : " << item;

if (q.GetNext(&item) == 0)
cout << "\nItem : " << item;
if (q.GetNext(&item) == 0)
cout << "\nItem : " << item;

if (q.PeekAtNext(&item) == 0)
cout << "\nPeek Item : " << item;

if (q.GetNext(&item) == 0)
cout << "\nItem : " << item;
if (q.GetNext(&item) == 0)
cout << "\nItem : " << item;
if (q.GetNext(&item) == 0)
cout << "\nItem : " << item;
cout << endl;
}

You might also like