Lecture 9: Recursion
recursion(recursion(recursion(recursion(recursion))))
A function that calls itself is known as recursive function and this technique is known as recursion in C programming.
Recursion 1
A simple example
void something(int foo) {
printf("%d\n", foo);
if(foo > 0) {
something(foo - 1);
}
}
int main(void) {
something(4);
return 0;
}
What will the function something print?
A slightly more complicated example
void something_else(int foo) {
printf("%d\n", foo);
if(foo > 0) {
something_else(foo - 1);
}
printf("%d\n", foo);
}
int main(void) {
something_else(4);
return 0;
}
What is printed by something_else?
A more useful example
int something(int n);
int main(){
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=something(num);
printf("something=%d",add);
}
int something(int n){
if(n==0)
return n;
else
return n+something(n-1); /*self call to function something() */
}
Guess the role of this function? What is the output if the input number is 5?
1: Function discussion partially from http://www.programiz.com/.