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. Logic to print all natural numbers in given range using recursion in C programming.

Required knowledge

Basic C programming, If else,for loop,Functions, Recursion

Declare recursive function to print natural numbers in given range

  1. First let us give a meaningful name to our function, say printNaturalNumbers().
  2. Next we need to print natural numbers in range. Hence, the function must accept two parameters i.e. start and end limit to print natural numbers. For that let us update our function declaration say printNaturalNumbers(int lowerLimit, int upperLimit);.
  3. Finally the function should print all natural numbers in given range returning nothing i.e. void.
    Function declaration to print all natural numbers in given range should look like void printNaturalNumbers(int lowerLimit, int upperLimit);

Logic to print natural numbers in given range using recursion

Base condition of recursive function to print natural numbers is loweLimit < upperLimit. Which is our required condition to return control from function. After checking base condition print the value of lowerLimit and make a recursive call to printNaturalNumbers() function i.e. printNaturalNumbers(lowerLimit + 1, upperLimit);.

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 printNaturalNumbers(int lowerLimit, int upperLimit);



int main()
{
    int lowerLimit, upperLimit;

    /* Input lower and upper limit from user */    
    printf("Enter lower limit: ");
    scanf("%d", &lowerLimit);
    printf("Enter upper limit: ");
    scanf("%d", &upperLimit);

    printf("All natural numbers from %d to %d are: ", lowerLimit, upperLimit);
    printNaturalNumbers(lowerLimit, upperLimit);
    
    return 0;
}


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

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



Output

Enter lower limit: 1

Enter upper limit: 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




Instagram