COURSE TITLE: COMPUTER PROGRAMMING I
COURSE CODE: CSC 203
NAME OF LECTURER: IBHARALU, F. I.
DEPARTMENT: COMPUTER SCIENCE
1
Recursions
C is a powerful programming language having capabilities like an iteration of
a set of statements 'n' number of times. The same concepts can be done using
functions also. In this part, you will be learning about recursion concept and
how it can be used in the C program.
2
What is Recursion
A recursive function is a function that calls itself again and again, and the process continues till a
specific condition is reached.
Here's an example of how recursion works in a program:
Example Syntax:
void recursivefunc(void)
{
//some statements
recursivefunc(); //function calls itself
//further statements
}
int main(void)
{
recursivefunc();
return 0;
}
3
C program allows us to define and use recursive functions, but when we
implement this recursion concept, we must be cautious in defining an exit or
terminating condition from this recursive function, or else it will continue to
an infinite loop, so make sure that the condition is set within your program.
Let’s take some examples.
Factorial Program in C using Recursion
Example:
#include<stdio.h>
#include<conio.h>
int fact(int f)
{
if (f == 0 || f == 1)
{
return 1;
}
return f * fact(f - 1);
} 5
int main(void)
{
int d = 12;
int f = fact(d);
printf ("The factorial of %d is %d \n", d, f);
getch();
return 0;
}
Output:
The factorial of 12 is 479001600
6
Fibonacci program in C using recursion:
The Fibonacci sequence is a series of numbers where a number is the sum of
the last two numbers, starting with 0 and 1.
The Fibonacci sequence is: 0, 1, 1, 2, 3,5, 8, 13, 21, 34, 55, …
7
Example:
#include<stdio.h>
#include<conio.h>
int fibo(int g)
{
if (g == 0)
{
return 0;
}
if (g == 1)
{
return 1;
}
return fibo(g - 1) + fibo(g - 2);
}
8
int main(void)
{
int g;
printf("Calculated Fibonacci\n");
for (g = 0; g < 10; g++)
{
printf("%d \t ", fibo(g));
}
getch();
return 0;
}
Output:
Calculated Fibonacci
0 1 1 2 3 5 8 13 21 34
9