C program to print all natural numbers from 1 to n using recursion

Write a recursive function in C programming to print all natural numbers between 1 to n. How to print all natural numbers from 1 to n using recursion in C program. Write a function in C program to display all natural numbers between a given range using the concept of recursion .

Example:
Input n: 10
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Required knowledge

Basic C programming, Function, Recursion

If you have gone through my earlier post how to print all natural numbers using loop then deriving the logic of this program wouldn't be difficult.

Program to print natural numbers from 1 to n using recursion

/**
 * C program to print all natural numbers from 1 to n using recursion
 */

#include <stdio.h>


/* Function declaration */
void printNaturalNumber(int lowerLimit, int upperLimit);



int main()
{
    int limit;
    
    printf("Print all natural numbers from 1 to : ");
    scanf("%d", &limit);
    
    printf("All natural numbers from 1 to %d are: ", limit);
    printNaturalNumber(1, limit);
    
    return 0;
}



/**
 * Recursively prints all natural number between the given range.
 */
void printNaturalNumber(int lowerLimit, int upperLimit)
{
    if(lowerLimit > upperLimit)
        return;
    
    printf("%d, ", lowerLimit);

    //Recursively calls the function to print next number
    printNaturalNumber(lowerLimit+1, upperLimit);
}


Output
Print all natural numbers from 1 to : 100
All natural numbers from 1 to 100 are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment