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




4 comments:

  1. Replies
    1. The program takes the value of n as input. The recursive function printUptoN() prints the numbers from 1 to n as the output.

      Delete
  2. how does it print from 1 to n .. please explai . im still confused

    ReplyDelete
    Replies
    1. I have tried to explain the recursive calls by the following example. I hope it will help.

      Suppose n = 3
      Calling the function from main(): printUptoN(3)

      printUptoN(3):
      Here n > 1 i.e. 3 > 1 is true, so call printUptoN(2)

      printUptoN(2):
      Here n > 1 i.e. 2 > 1 is true, so call printUptoN(1)

      printUptoN(1):
      Here n > 1 i.e. 1 > 1 is false, so print 1

      Now printUptoN(1) was called from printUptoN(2), so go back to printUptoN(2).
      So print 2

      Now printUptoN(2) was called from printUptoN(3), so go back to printUptoN(3).
      So print 3

      Now printUptoN(3) was called from main(), so go back to main().



      Delete

If you have any doubts or suggestions, please leave a note.