C Program To Print Natural Numbers using Recursion

Lets write a C program to print/display natural numbers from 1 to user entered limit, using recursive function calls.

Related Read:
C Program to Print Natural Numbers from 1 to N using While loop
C Program to Print Natural Numbers from 1 to N using for loop
Recursive Functions In C Programming Language

Video Tutorial: C Program To Print Natural Numbers from 1 To N using Recursion



YouTube Link: https://www.youtube.com/watch?v=Ji574fawdfo [Watch the Video In Full Screen.]


Source Code: C Program To Print Natural Numbers using Recursion

#include<stdio.h>

void display(int);

int main()
{
    int limit;

    printf("Enter the number of terms to be printed\n");
    scanf("%d", &limit);

    printf("\nNatural Numbers from 1 To %d are:", limit);
    display(limit);

    return 0;
}

void display(int num)
{
    if(num)
        display(num-1);
    else
        return;

    printf("\n%d\n", num);
}

Output:
Enter the number of terms to be printed
14

Natural Numbers from 1 To 14 are:
1

2

3

4

5

6

7

8

9

10

11

12

13

14

Logic To Print Natural Numbers using Recursion

We ask the user to input the limit or the number of terms of natural numbers to be printed. We store that value inside variable limit. We pass this value to a function called display().

Inside display() function
We check if number is not zero, in that case we call the same function display() recursively and pass (num-1) to it. In the else block we write the base condition, that is, return the control back to the calling function if num is 0.

This prints the natural numbers from 1 to user input limit.

Example:

If limit = 5. We copy the value of limit to num. So num = 5.

num Calling Function Called Function
5 main() display(5)
5 display(5) display(4)
4 display(4) display(3)
3 display(3) display(2)
2 display(2) display(1)
1 display(1) display(0)
returns the control back display(0) return;

Value Returning – Control Shifting back.

Function Return Value
return;
display(0) 1
display(1) 2
display(2) 3
display(3) 4
display(4) 5

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert