Repetition via Recursion

Lecture 13
Recursion part 2
Richard Gesick
Advanced Recursion
• Sometimes recursion involves processing a
• While it could be done using 'foreach' or some
other iterative approach, recall that recursion
works best for non-linear structures.
• Recursion is also useful for making use of the
activation stack as a "reminder" of where we've
been and what remains to be done.
multiple recursion
Consider this example: what is DoWork(5) ?
void DoWork(int i)
if (i > 2)
multiple recursion (2)
• Fibonacci series: an= a(n-1) +a(n-2) i.e. the
next number in the series is the sum of the
2 preceding numbers.
• the Fibonacci series: 1,1,2,3,5,8,13,…
• Write a multiply recursive method:
int Fibo ( int n)
• (Remember stopping state first!)
The solution
int Fib(int i)
if (i < 2)
return 1;
return Fib(i-1) + Fib(i-2);
String Processing
How can we reverse a string recursively?
Pseudo-code solution
(base case is when string is ? ):
reverse a string by repeatedly
removing the first character,
reversing this substring (recursively),
appending the first character to the end
string reversal code
static string Reverse (string s)
if (s.Length==1)
return s;
return Reverse(s.Substring(1)) + s[0];
Non-linear Recursion
• Folders and files within a computer system
are an excellent example of a non-linear
structure that is easily processed via
• This is also possible using iteration, but we
would have more coding work to do in
handling where we've been in the file
• We can leverage the activation stack to
remember for us.
Non-linear Recursion
• Consider the steps to count the total number of files:
If we're in a folder with no files (or subfolders),
then we return 0
Otherwise, we return the count of the files in the
folder + all the files in the subfolders
• It's the second part that's tricky... but notice that's
where the recursive call comes in. We just need to
recursively call for each subfolder (so this is
recursion wrapped inside of iteration):
private int CountFiles(DirectoryInfo di)
int file_count = 0;
file_count += di.GetFiles().Length;
foreach (DirectoryInfo sub_folder in di.GetDirectories())
file_count += CountFiles(sub_folder);
return file_count;