Example:
Input n: 10
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Required knowledge
Basic C programming, Function, RecursionIf 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,
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 ;)
You may also like
- Function and recursion programming exercises index.
- C program to print all even or odd numbers from 1 to n using recursion.
- C program to find sum of all natural numbers from 1 to n using recursion.
- C program to find sum of all even or odd numbers using recursion.
- C program to find power of any number using recursion.
- C program to find sum of digits of any number using recursion.
- C program to find factorial of any number using recursion.
- C program to find LCM of two numbers using recursion.
- C program to print all prime numbers between given interval using recursion.
- C program to check whether the number is prime, Armstrong or perfect using functions.