C program to print even or odd numbers between 1 to n using recursion

Write a recursive function in C programming to print all even or odd numbers between 1 to n. How to print all even numbers in a given range using recursion in C programming. How to print all odd numbers in a given range using recursion in C programming.

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, Recursion

If 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,

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment