C Program to Print All Natural Numbers Using Recursion

First N natural numbers

C program to print all the natural numbers from 1 to N can be written in both iterative and recursive methods. In the recursive method, the task can be performed by calling a recursive function N times to print a natural number in each call. Here, the recursive method in C to print the natural numbers from 1 to N (1, 2, 3, ..., N) has been shown.






1. C Program & output to Print First N Natural Numbers using Recursion

Code has been copied
/**********************************************
            alphabetacoder.com
 C program to print all natual numbers from 1 
 to n using recursion
*********************************************/

#include <stdio.h>
 // recursive function
void printUptoN(int n) {
    //condition for calling
    if (n > 1)
        printUptoN(n - 1);
    printf("%d ", n);
}
int main() {
    int n;
    //take input of the number upto which 
    // natural numbers will be printed
    printf("Enter the upper limit = ");
    scanf("%d", & n);

    printf("First %d natural numbers are : ", n);
    // call the recursive function to print
    // the natural numbers
    printUptoN(n);

    return 0;
}

Output


Case 1:

Enter the upper limit = 4

First 4 natural numbers are : 1 2 3 4


Case 2:

Enter the upper limit = 8

First 8 natural numbers are : 1 2 3 4 5 6 7 8