A function that calls itself is called recursion function.
Syntax:
void recurse(){
....
recurse();
...
}
int main(){
....
recurse();
....
return 0;
}
In the above code the function recurse() will call itself again and again.
To prevent it we can add if else statement.
void recurse(){
if(condition){
....
}
else{
recurse();
}
...
}
Task 1: Program to find the sum of n natural numbers.
#include <stdio.h>
int main() {
int number, result;
printf("Enter a number: ");
scanf("%d", &number);
result = findSum(number);
printf("Sum = %d", result);
return 0;
}
int findSum(int num){
if(num!=0){
return num + findSum(num - 1);
}else{
return 0;
}
}
Task 2: Program to find the factorial of a number:
#include <stdio.h>
int main() {
int number, result;
printf("Enter a number: ");
scanf("%d", &number);
result = findSum(number);
printf("Sum = %d", result);
return 0;
}
int findSum(int num){
if(num!=0){
return num * findSum(num - 1);
}else{
return 1;
}
}
Top comments (0)