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

PF-CE Lab12 Recursive Algorithms

The document is a laboratory manual for a programming fundamentals course focused on recursive algorithms. It includes objectives, examples of recursive functions, and tasks for students to implement various recursive solutions in C++. The manual covers topics such as calculating factorials, Fibonacci numbers, string reversal, and the Tower of Hanoi problem.

Uploaded by

mashnabsafdar
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)
3 views

PF-CE Lab12 Recursive Algorithms

The document is a laboratory manual for a programming fundamentals course focused on recursive algorithms. It includes objectives, examples of recursive functions, and tasks for students to implement various recursive solutions in C++. The manual covers topics such as calculating factorials, Fibonacci numbers, string reversal, and the Tower of Hanoi problem.

Uploaded by

mashnabsafdar
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/ 12

Programming Fundamentals

(CL1002)

LABORATORY MANUAL
BS-CE, Spring 2025

LAB 12
Implementation of Recursive Algorithms

Muhammad Ashnab Safdar I24-6500 CE-A

STUDENT NAME ROLL NO SEC

______________________________________

LAB ENGINEER'S SIGNATURE & DATE


Muhammad Hammad

MARKS AWARDED: /10


_____________________________________________________________________
NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES (NUCES), ISLAMABAD
Prepared by: Engr. Aamer Munir, Muhammad Hammad Version: 1.1
Date last
Last edited by: Engr. Azhar Rauf, Engr. Aamer Munir Sep 27, 2018
edited:
Date last
Verified by: Engr. Azhar Rauf Jan 10, 2025
edited:
Recursive Functions LAB 12

Lab Objectives:
1. To learn about Recursion .

2. To implement recursive algorithms. .

Software Required:
 Code: Dev C++

Introduction:

1. Recursive Functions

A recursive function is one that calls itself. You have seen instances of
functions calling other functions. Function A can call function B, which can
then call function C. It’s also possible for a function to call itself. A function
that calls itself is a recursive function. Look at this message function:

void message()
{
cout << "This is a recursive function.\n";
message();
}

This function displays the string “This is a recursive function.\n” and then
calls itself. Each time it calls itself, the cycle is repeated. There’s no way to
stop the recursive calls. This function is like an infinite loop because there is
no code to stop it from repeating. The function message will eventually
cause the program to crash. Eventually, these recursive function calls will
use up all available stack memory and cause it to overflow.

Like a loop, a recursive function must have some method to control the
number of times it repeats. The following is a modification of the message
function. It passes an integer argument, that holds the number of times the
function is to call itself.

void message(int times)


{
if (times > 0)
{
cout << "This is a recursive function.\n";
message(times − 1);
}
}

PF LAB 12 NUCES, ISLAMABAD Page 2 of 12


Recursive Functions LAB 12
This function contains an if statement that controls repetition. If the times
argument is greater than zero, it will display the message and call itself
again. Each time it calls itself, it passes times − 1 as the argument. For
example, let’s say a program calls the function with the following statement:

message(5);

The argument, 5, will cause the function to call itself five times. The first
time the function is called, the if statement will display the message and
then call itself with 4 as the argument.

PF LAB 12 NUCES, ISLAMABAD Page 3 of 12


Recursive Functions LAB 12
The above diagram illustrates six separate calls of the message function.
Each time the function is called, a new instance of the times parameter is
created in memory. The first time the function is called, the times parameter
is set to 5. When the function calls itself, a new instance of times is created,
and value 4 is passed into it. This cycle repeats until, finally, zero is passed
to the function.

As you can see from Figure that the function is called a total of six times.
The first time it is called from main, and the other five times it calls itself, so
the depth of recursion is five. When the function reaches its sixth call, the
times parameter will be set to 0. At that point, the if statement’s conditional
expression will be false. So, the function will return. Control of the program
will return from the sixth instance of the function to the point in the fifth
instance directly after the recursive function call:

Because there are no more statements to be executed after the function


call, the fifth instance of the function returns control of the program back to
the fourth instance. This repeats until all instances of the function return.

Example 1:

#include <iostream>
using namespace std;
void message(int);
int main()
{
message(5);
return 0;
}

void message(int times)


{
if (times > 0)
{
cout << "This is a recursive function.\n";
message(times − 1);
}

PF LAB 12 NUCES, ISLAMABAD Page 4 of 12


Recursive Functions LAB 12
}

To further illustrate the inner workings of this recursive function, let’s look at
another version of the program.

Example 2:

#include <iostream>
using namespace std;
void message(int);

int main()
{
message(5);
return 0;
}

void message(int times)


{
cout << "message called with " << times << " in times.\n";
if (times > 0)
{
cout << "This is a recursive function.\n";
message(times − 1);
}
cout << "message returning with " << times;
cout << " in times.\n";
}

2. Solving a Problem with Recursive Function

A problem can be solved with recursion if it can be broken into successive


smaller problems that are identical to the overall problem. Recursion can be
a powerful tool for solving repetitive problems. It simplifies the complex
problems by dividing them in smaller problems. Recursion also reduces the
complexity of code. To use recursive function approach , we first identify at
least one case in which the problem can be solved without recursion. This
is known as the base case. Second, we determine a way to solve the
problem in all other circumstances using recursion. This is called the
recursive case. In the recursive case, we must always reduce the problem
to a smaller version of the original problem. By reducing the problem with
each recursive call, the base case will eventually be reached, and the
recursion will stop.

PF LAB 12 NUCES, ISLAMABAD Page 5 of 12


Recursive Functions LAB 12

Example 3:

//Recursive function to calculate factorial

#include <iostream>
using namespace std;
int factorial(int);

int main()
{
int number;

cout << "Enter an integer value and I will display\n";


cout << "its factorial: ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
return 0;
}

int factorial(int n)
{
if (n == 0)
return 1; // Base case
else
return n * factorial(n − 1); // Recursive case
}

PF LAB 12 NUCES, ISLAMABAD Page 6 of 12


Recursive Functions LAB 12

Tasks
Task01:

PF LAB 12 NUCES, ISLAMABAD Page 7 of 12


Recursive Functions LAB 12
Calculate the factorial of first n numbers using code given in example 3 where n
should be input from user.
#include <iostream>
using namespace std;
int factorial(int);

int main()
{
int number;

cout << "Enter an integer value and I will display the \n";
cout << "factorials of all the numbers smaller than it including the number: ";
cin >> number;
for(int i =number;i>=number,i>=0;i--){
cout << "The factorial of " << i << " is ";
cout << factorial(i) << endl;}
return 0;
}

int factorial(int n)
{
if (n == 0)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive case
}

Task02:

Write a C++ program to create a recursive function power(x,y) which should


recursively calculate xy where x (base) and y (exponent) are input.

PF LAB 12 NUCES, ISLAMABAD Page 8 of 12


Recursive Functions LAB 12

#include <iostream>
#include <cmath>
using namespace std;
int Fibo(int);
int main()
{
int n;
cout<<"Enter the nth term of fibonacci series : "<<endl;
cin>>n;
for(int i=0;i<=n;i++)
{cout<<Fibo(i);
if (i != n) {
cout << ", ";
}
}
return 0;
}

int Fibo(int n)
{ if (n == 0)
return 0; // Base case
if (n == 1)
return 1;
else
return Fibo(n-1) + Fibo(n - 2); // Recursive case
}

Task03:

Write a recursive function to calculate the nth Fibonacci number using the following
recursive function.
F(n) = F(n-1) + F(n-2) where F(0) = 0 and F(1) = 1.
#include <iostream>
#include <cmath>
using namespace std;
int Fibo(int);
int main()
{
int n;
cout<<"Enter the nth term of fibonacci series : "<<endl;
cin>>n;
cout<<Fibo(n);
return 0;
}

int Fibo(int n)

PF LAB 12 NUCES, ISLAMABAD Page 9 of 12


Recursive Functions LAB 12
{ if (n == 0)
return 0; // Base case
if (n == 1)
return 1;
else
return Fibo(n-1) + Fibo(n - 2); // Recursive case
}

Task04:

Write a recursive function to calculate the sum of first n numbers where n is the input.
#include <iostream>
#include <cmath>
using namespace std;
int Sum(int);
int main()
{
int n;
cout<<"Enter the nth number to find the sum of all the number smaller than it : "<<endl;
cin>>n;
cout<<"The sum is : "<<Sum(n) ;
return 0;
}

int Sum(int n)
{ if (n == 0)
return 0; // Base case

else
return n +Sum(n-1); // Recursive case
}

Task05:

Write a recursive function to reverse a string without using loops.


#include <iostream>
using namespace std;
void reverseString(string& str, int start, int end) {

PF LAB 12 NUCES, ISLAMABAD Page 10 of


12
Recursive Functions LAB 12

if (start >= end) {


return;
}
swap(str[start], str[end]);
reverseString(str, start + 1, end - 1);
}

int main() {
string myString;

cout << "Enter a string: ";


getline(cin,myString) ;

reverseString(myString, 0, myString.length() - 1);

cout << "Reversed string: " << myString << endl;

return 0;
}

Bonus Task.

Write a report on the problem of Tower of Hanoi and write the recursive function to solve
the problem. Online help may be taken.

#include<iostream>
using namespace std;

int moveCount = 0;

void hanoi(int n , int source , int helper , int destination)


{
if (n == 1)
{
cout << "Move disk 1 from rod " << source << " to rod " << destination << endl;
moveCount++;
return;
}

hanoi(n - 1, source, destination, helper);


cout << "Move disk " << n << " from rod " << source << " to rod " << destination <<
endl;
moveCount++;
hanoi(n - 1, helper, source, destination);

PF LAB 12 NUCES, ISLAMABAD Page 11 of


12
Recursive Functions LAB 12
}

int main()
{
int number;
cout << "Enter the number of disks: ";
cin >> number;

if (number <= 0)
{
cout << "Please enter a positive number of disks." << endl;
return 1;
}

cout << "\nSequence of moves:\n" << endl;


hanoi(number, 1, 2, 3);

cout << "\nTotal moves: " << moveCount << endl;


return 0;
}

PF LAB 12 NUCES, ISLAMABAD Page 12 of


12

You might also like