DEV Community

Sujith V S
Sujith V S

Posted on

Recursion in C programming.

A function that calls itself is called recursion function.

Syntax:

void recurse(){
    ....
    recurse();
    ...    
}

int main(){
    ....
    recurse();
    ....
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

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();
    }
    ...    
} 
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)