Docsity

Recursion: A Powerful Programming Technique for Problem Solving, Exams of Computer Science

Toggle sidebar
bg1
Recursion
Recursion is a function invoking itself, either directly or
indirectly.
It can be used as an alternative to iteration.
Recursion is an important and powerful tool in problem
solving and programming. It is a programming technique
that naturally implements the divide-and-conquer
problem solving methodology.
In its simplest form the idea of recursion is straightforward:
Example 1:
void count_down(int n)
{
if (n <= 0)
printf(“\nBlast off.\n”);
else{
printf(“%d! “, n);
count_down(n-1);
}
}
int main ()
{
count_down(10);
}
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download Recursion: A Powerful Programming Technique for Problem Solving and more Exams Computer Science in PDF only on Docsity!

Recursion

 Recursion is a function invoking itself, either directly or indirectly.  It can be used as an alternative to iteration.  Recursion is an important and powerful tool in problem solving and programming. It is a programming technique that naturally implements the divide-and-conquer problem solving methodology. In its simplest form the idea of recursion is straightforward: Example 1: void count_down(int n) { if (n <= 0) printf(“\nBlast off.\n”); else{ printf(“%d! “, n); count_down(n-1); } } int main () { count_down(10); }

Example 2: Multiplication of natural numbers.

a * b = a added to itself b times. (iterative definition)

a * b = a if b=

(recursive definition)

a* b = a * (b-1) + a if b > 1

e.g.

In C:

int multiply(int a, int b) { if (b == 1) / stopping case / return a; else / recursive step / return ( a + multiply(a, b-1)); }

Thus,

n! = 1 if n = 0

n! = n*(n-1)! if n > 0

In C:

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

The Nature of Recursion

1) One or more simple cases of the problem (called

the stopping cases ) have a simple non-recursive

solution.

2) The other cases of the problem can be reduced

( using recursion ) to problems that are closer to

stopping cases.

3) Eventually the problem can be reduced to

stopping cases only, which are relatively easy to

solve.

In general:

if (stopping case)

solve it

else

reduce the problem using recursion

Tracing a Recursive Function

Computer uses a stack to keep track of function calls.

Whenever a new function is called, all its parameters

and local variables are pushed onto the stack along

with the memory address of the calling statement

(this gives the computer the return point after

execution of the function)

Example: Tracing a Recursive Function

Palindrome is a string of characters that reads the

same backwards and forwards (e.g. level, deed, mom)

palindrome(5) reads 5 characters and prints them in

reverse order.

void palindrome(int n) { char next; if (n == 1) { / stopping case / scanf("%c",&next); printf("%c", next); } else { scanf("%c", &next); palindrome(n-1); printf("%c",next); } return; } int main() { printf("Enter a string: "); palindrome(5); printf("\n"); }

Trace of palindrome: for input abc

palindrome(3);

n= 3 <= 1? false read next : a palindrome(2) write a return n= 2 <= 1? false read next : b palindrome(1) write b return n= 1 <= 1? true read next : c write c return

Common Errors

 It may not terminate if the stopping case is not

correct or is incomplete (stack overflow: run-time

error)

 Make sure that each recursive step leads to a

situation that is closer to a stopping case.

Comparison of Iteration and Recursion

 In general, an iterative version of a program will

execute more efficiently in terms of time and space

than a recursive version. This is because the

overhead involved in entering and exiting a

function is avoided in iterative version.

 However a recursive solution can be sometimes the

most natural and logical way of solving a problem.

 Conflict: machine efficiency versus

programmer efficiency

 It is always true that recursion can be

replaced with iteration and a stack.

Problem Solving with Recursion

Towers of Hanoi Problem : involves moving a

specified number of disks (N) that are all different

sizes from one tower to another.

The goal is to move all disks from tower A to C

subject to the following rules:

1. Only one disk may be moved at a time and this

disk must be the top disk on a tower.

2. A larger disk can never be placed on top of a

smaller disk.

The stopping cases of the problem involve moving

only one disk.

Problem : Solve the Towers of Hanoi for N disks.

Analysis : Solution consists of a printed list of

individual disk moves. We need recursion that can be

used to move any number of disks from one tower to

another, using the third tower as a temporary tower.

Inputs : n: integer,

start:’A’, ‘B’, or ‘C’,

finish:’A’, ‘B’, or ‘C’

temp:’A’, ‘B’, or ‘C’

Output : a list of individual disk moves.

Algorithm

if (n == 1) /* stopping case */

move a single disk from start to finish

else

-Move n-1 disks from start to temp using finish

as temporary tower.

_- Move a single disk from start to finish

  • Move_ n-1 disks from temp to

finish using start as temporary tower

In C:

void tower(int n, char start, char finish, char temp) { if (n == 1) printf(“Move from %c to %c\n”, start, finish); else { tower(n-1, start, temp, finish); printf(“Move from %c to %c \n”, start, finish); tower(n-1, temp, finish, start); } }

Test:

tower(3,‘A’,’C’, ’B’);

Output:

Move from A to C Move from A to B Move from C to B Move from A to C Move from B to A Move from B to C Move from A to C

  1. Trace the following recursive function: #include <stdio.h> int f(int c) { if (!(c > 10)) { printf("%d\n", c); f(c + 1); } } int main() { f(0); }
  1. Trace the following recursive function: #include <stdio.h> void f(int); void g(int); void f(int c) { printf("hello from f()\n"); if (++c <= 3) g(c); } void g(int c) { printf("hello from g()\n"); f(c); } int main() { printf("hello from main\n"); f(1); return 0; }

5) Write a recursive function to check if the contents

of an array are in ascending order or not. The

function prototype is:

/* Inputs: an integer array, the index of the last element in the array. Output: true or false. */ int isAscending(int a[], int n);