Transcript Lecture 21

Introduction to C
Programming
CE00312-1
Lecture 21
Recursion and
Linear Linked Lists
Factorial of an Integer
Factorial of 6 is expressed as 6!
whose value is
654321
or it can be rewritten as
65!
We have defined 6! in terms of 5! - a recursive definition
In general
and
n! is n(n-1)! when n > 0
0! is 1
Factorial as a C function
int fact (int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * fact(n - 1);
}
}
An equivalent “functional” version is:
int fact(int n)
{
return (n == 0 ? 1
: n * fact(n - 1));
}
This can be read as
“return the result of
if n is 0 then 1 else factorial of n-1”.
Recursion with Linear Linked
Lists

Recursive functions are more convenient,
shorter and easier to modify (once you get
used to them!) compared to iterative
functions (ie with while loops).
Printing a linear linked list
list
3
Print 3
5
then
8
Print the rest
12
-
Recursive function print_list
#include "LLL.h“ // node structure, type
void print_list(Listpointer list)
{
if (list != NULL)
// not empty list
{
printf("%d\n", list -> value);// print first
print_list(list -> next);
// print rest
}
// else empty list do nothing
}
For the current node given by, pointer list, print its value
and then the recursive call, print_list, deals with the rest.
Printing a linear linked list in
reverse
list
3
5
8
12
Print the rest in reverse
then
print 3
-
Print the list in reverse
#include "LLL.h“ // node structure, type
void print_reverse(Listpointer list)
{
if (list != NULL)
// not empty list
{
print_reverse(list -> next); // print rest
printf("%d\n", list -> value);// print first
}
// else empty list do nothing
}
This function recurses down the list, including the last,
and prints values as it returns back up the list.
Adding the items in a linear
linked list
list
3
3
5
+
8
sum of the rest
12
-
Recursive function to add all
the items in a list
int sum(Listpointer list)
{
if (list == NULL)
{
return 0;
// empty list, sum is 0
}
else
{
return list->value + sum(list->next);
}
}
The previous function could also be written as:
int sum(Listpointer list)
{
return (list == NULL)
? 0
: list -> value
+ sum(list -> next);
}
This can be read as “return the result of
if the list is empty then zero
else this node’s value plus the sum of the rest”