DEV Community

Sujith V S
Sujith V S

Posted on

2 1 1 1 1

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay