Example:
Input range: 10
Output even numbers: 2, 4, 6, 8, 10
Output odd numbers: 1, 3, 5, 7, 9
Required knowledge
Basic C programming, Function, RecursionIf you have gone through my previous post how to print natural numbers using recursion you will probably find that the logic of this program is pretty much similar to the previous program.
Program to print even or odd numbers between 1 to n using recursion
/** * C program to print even or odd numbers in given range using recursion */ #include <stdio.h> /* Function declaration */ void printEvenOdd(int cur, int limit); int main() { int limit; //Reads limit from user printf("Enter the range to print: "); scanf("%d", &limit); printf("All even numbers from 1 to %d are: ", limit); printEvenOdd(2, limit); printf("\n\nAll odd numbers from 1 to %d are: ", limit); printEvenOdd(1, limit); return 0; } /** * Prints even or odd numbers in a given range using recursion. Prints all even * numbers if cur is even otherwise prints all odd numbers. */ void printEvenOdd(int cur, int limit) { if(cur > limit) return; printf("%d, ", cur); //Recursively calls the next even or odd number to be printed. printEvenOdd(cur+2, limit); }
Output
Enter the range to print: 100
All even numbers from 1 to 100 are: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100,
All odd numbers from 1 to 100 are: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99,
All even numbers from 1 to 100 are: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100,
All odd numbers from 1 to 100 are: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99,
Happy coding ;)
You may also like
- Function and recursion programming exercises index.
- C program to find sum of even or odd numbers in given interval using recursion.
- C program to print all natural numbers within given interval using recursion.
- C program to find factorial of any number using recursion.
- C program to generate nth fibonacci term using recursion.
- C program to find GCD(HCF) of any two numbers using recursion.
- C program to find LCM of any two numbers using recursion.
- C program to display array elements using recursion.
- C program to find cube of any number using function.
- C program to find maximum and minimum between two numbers using functions.
- C program to check even or odd numbers using function.