Broad Network


Recursive Function in the C Computer Language

Part 30 of the Complete C Course

Foreword: Recursive Function in the C Computer Language

By: Chrysanthus Date Published: 22 Jun 2024

Introduction

A recursive function is a function that keeps calling itself from within the function, repeatedly until a condition is met. Two situations should be considered: a recursive function that returns void and a recursive function that returns a value.

A Recursive Function that returns void
The following function counts integers from 0 to 4. The condition is that the incrementing variable, i should not be equal to 5 or greater.

    #include <stdio.h>
    
    void fn (int i) {
        printf("%i ", i);
        i = i + 1;
        if (i < 5)
            fn(i);
    }
    
    int main(int argc, char *argv[])
    {
        fn(0);
        printf("\n");

        return 0;
    }

The function of interest is fn(). It has only one argument. When called the first time, the argument is 0. The first statement in the function prints the current number, and a space. The second statement increments the number: 1 is added to the previous value of i on the right-hand-side of = ; and the result becomes the new value of i, which is on the left-hand-side of = . The condition to stop the recursion is the condition of the if-statement. As long as (i < 5) is true, fn(i) is called, where i here is the next number. The output is:

    0 1 2 3 4

A Recursive Function that returns a Value
For this kind of recursion, if the return value is the next only input, then just return the function call. The following function, fn() repeats the above, by just returning the function call, in the if-simple statement:

    #include <stdio.h>
    
    int fn(int i) {
        printf("%i ", i);
        i = i + 1;
        if (i < 5)
            return fn(i);
    }
    
    int main(int argc, char *argv[])
    {
        fn(0);
        printf("\n");

        return 0;
    }

The output is the same.





Related Links

More Related Links

Cousins

BACK NEXT

Comments