You are on page 1of 7

COMSATS University Islamabad

Islamabad Campus
Data Structure and Algorithm
Instructor: Shawana jamil
Lab-8

Due date: April 10th 2019

In this lab we will introduce you concept of Recursion and Implement Queue data structure
Objective:
The objective of this lab
1. Is to implement Recursion
2. is to implement queue ADT.
Recursion:
How to formulate programs recursively.
How to apply the three laws of recursion.
How to implement the recursive formulation of a problem.

1) Stage J (Journey)
Introduction
An algorithm is recursive if it calls itself to do part of its work. For this approach to be successful,
the ―call to itself‖ must be on a smaller problem then the one originally attempted. In general, a
recursive algorithm must have two parts: the base case, which handles a simple input that can be
solved without resorting to a recursive call, and the recursive part which contains one or more
recursive calls to the algorithm where the parameters are in some sense ―closer‖ to the base case
than those of the original call.
We divide/decompose the problem into smaller (sub) problems:

 Keep on decomposing until we reach to the smallest sub-problem (base case) for which a solution
is known or easy to find

 Then go back in reverse order and build upon the solutions of the subproblems
A recursive function is defined in terms of base cases and recursive steps.

• In a base case, we compute the result immediately given the inputs to the function call.

• In a recursive step, we compute the result with the help of one or more recursive calls to this same
function, but with the inputs somehow reduced in size or complexity, closer to a base case.

What Happens When a Method is called?

Activation records (AR) will store the following information about the method:
• Local variables of the method.
• Parameters passed to the method.
• Value returned to the calling code (if the method is not a void type).
• The location in the calling code of the instruction to execute after returning from the called
method.

Two ways of thinking:

For something simple to start with – let’s write a function pow(x, n) that raises x to a natural power of n.
In other words, multiplies x by itself n times.

pow(2, 2) = 4 pow(2, 3) = 8
pow(2, 4) = 16
There are two ways to implement it.
Iterative thinking: the for loop:
1. function pow(x, n) {
2. let result = 1;
3. // multiply result by x n times in the loop
4. for (let i = 0; i < n; i++) {
5. result *= x;
6. }
7. return result;
8. }

Recursive thinking: simplify the task and call self:


1. function pow(x, n) {
2. if (n == 1) {
3. return x;
4. } else {
5. return x * pow(x, n - 1);
6. }
7. }

When pow(x, n) is called, the execution splits into two branches:


if n==1 = x (Base case)
/
pow(x, n) =
\
else = x * pow(x, n - 1) (Recursive call)
If n == 1, then everything is trivial. It is called the base of recursion, because it immediately produces the
obvious result: pow(x, 1) equals x.
Otherwise, we can represent pow(x, n) as x * pow(x, n - 1). In maths, one would write xn = x *
xn-1. This is called a recursive step: we transform the task into a simpler action (multiplication by
x) and a simpler call of the same task (pow with lower n). Next steps simplify it further and further
until n reaches 1.

Activity 1: Write a recursive program to calculate factorial of a number


Activity 2: Write a recursive program to calculate sum of numbers from 1 to n.
Activity 3: Write a recursive program to store data in reverse order in an array Solution:
#include <bits/stdc++.h>
using namespace std;

/* Function to reverse arr[] from start to end*/ void rvereseArray(int arr[],


int start, int end)
{ if (start >= end)
return;

int temp = arr[start]; arr[start] = arr[end];


arr[end] = temp;

// Recursive Function calling


rvereseArray(arr, start + 1, end - 1);
}
/* Utility function to print an array */ void printArray(int arr[], int
size)
{ for (int i = 0; i < size; i++)
cout << arr[i] << " ";

cout << endl;


}

/* Driver function to test above functions */


int main() {
int arr[] = {1, 2, 3, 4, 5, 6};

// To print original array


printArray(arr, 6); // Function calling
rvereseArray(arr, 0, 5);

cout << "Reversed array is" << endl;

// To print the Reversed array printArray(arr, 6);

return 0;
}
Home Activities:
1) Write the recursive method to find the binary number of decimal number given by user.
2) Write the method which takes the integer value (n) as input and prints the sequence of numbers
from n to 0 in descending order.
3) Write a recursive function to compute first N Fibonacci numbers. Test and trace for N = 6
1 1 2 3 5 8
4) Write a recursive function that has a parameter representing a list of integers and returns the
maximum stored in the list. Thinking recursively, the maximum is either the first value in the list
or the maximum of the rest of the list, whichever is larger. If the list only has 1 integer, then its
maximum is this single value, naturally.

Queue
2
A queue is also a special case of a singly-linked list, which works according to FIFO algorithm. Of
the two ends of the queue, one is designated as the front − where elements are extracted
(operation called dequeue), and another is the rear, where elements are inserted (operation called
enqueue). A queue may be depicted as in Figure below:

The main operations are:


Enqueue − place an element at the tail of the queue;
Dequeue − take out an element form the front of the queue; Delete − delete
the whole queue

Scope:
An array of a given size will be declared and used as a queue data structure. The operations of
insertion at the rear end and deletion from the front end will be performed. In addition, the
display operation will show all the contents of queue from front to rear.
For linked based queue a structure of integer nodes will be declared. Then using this structure a
queue of integers will be created dynamically. Typical operation of insertion and deletion for this
queue will be implemented.

Example: This program demonstrates insertion and display of an array based queue.
/*Program of queue using array*/
# include<iostream.h>
# define MAX 5
int queue_arr[MAX];
int rear = ­1;
int front = ­1;
main(){
int choice;
while(1) {
cout<<"1.Insert\n";
cout<<"2.Display\n";
cout<<"3.Quit\n";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice){
case 1 :
insert(); break;
case 2 :
display(); break;
case 3:
exit(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/
insert(){
int added_item;
if (rear==MAX­1)
cout<<"Queue Overflow\n";
else {
if (front==­1) /*If queue is initially empty */
front=0;
cout<<"Input the element for adding in queue : ";
cin>>added_item;
rear=rear+1;
queue_arr[rear] = added_item ;
}
}/*End of insert()*/
display(){
int i;
if (front == ­1)
cout<<"Queue is empty\n";
else {
cout<<"Queue is :\n";
for(i=front;i<= rear;i++)
cout<<queue_arr[i];
cout<<endl;
}
}/*End of display() */

Example: This program demonstrates insertion and display of a pointer based queue.
/* Program of queue using linked list*/
# include<iostream.h>
struct node{
int info;
struct node *link;
}*front=NULL,*rear=NULL;
main(){
int choice;
while(1){
cout<<"1.Insert\n";
cout<<"2.Display\n";
cout<<"3.Quit\n";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice){
case 1:
insert(); break;
case 2:
display(); break;
case 3:
exit(1);
default :
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/
insert(){
struct node *tmp;
int added_item;
tmp = new node;
cout<<"Input the element for adding in queue : ";
cin>>added_item;
tmp­>info = added_item;
tmp­>link=NULL;
if(front==NULL) /*If Queue is empty*/
front=tmp;
else
rear­>link=tmp;
rear=tmp;
}/*End of insert()*/
display(){
struct node *ptr;
ptr = front;
if(front == NULL)
cout<<"Queue is empty\n";
else {
cout<<"Queue elements :\n”;
while(ptr != NULL){
cout<<ptr­>info;
ptr = ptr­>link;
}
printf("\n");
}/*End of else*/
}/*End of display()*/

Exercises:
1. Write a function to delete a value from an array based queue of integers.
2. Write a function to create circular queue. Perform enque and deque operation in circular queue

Home Work:
1. Write a function to delete a value from a pointer based queue of integers.
2. Write a function to create priority queue.
3. Message Sending System:
Consider a message sending system. Messages are sent by the sending station and are received by the receiving
station. At the receiving station, when the messages are received they are added to list of unread messages.
When a message is read, it is removed from list of unread messages. Create a queue to maintain list of
messages.
Each message on the queue corresponds to one node. Each message or node contains the following items:
- Message title (e.g circular, invoice, manager letter … )
- Message number
- Sender name
- Recipient name
- Message
When the messages are created and sent they are added to the message-list and once they are read/received they
are removed from list.

Create a queue program that manages this message-list.


Data Members:
- a node – which corresponds to a message includes Message title ,Message number, Sender name,
Recipient name, Message
.
Functions:
- Enqueue: Inserts new element x at the rear of queue by creating a new node and appending it to the
existing list. Will be called when message has to be sent.
- Dequeue: Deletes the first element(pointed to by front) of queue. Will be used when message is
read/received.
- Front: Displays an element from front of queue without deleting.
- Back: Displays an element from rear of queue without deleting.
- IsEmpty: a Boolean function that returns true if and only if queue is an empty queue.
- Length: Returns an integer value equal to the total elements present in a queue.
- Display: Display all elements present in a queue.
- Search: search function takes from user a name from user i.e “sender name”; matches this name with
the sender names of massages placed on queue and displays the result if a match is found.

2. Create a new field in the message list; ‘Priority’. Assign value to it based on message title. e.g. a manager
letter gets priority 1, an invoice gets priority 2 and so on. Modify the program such that it first finds the message
of highest priority in the list, and then dequeues it.

**********************

You might also like