w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Print even or odd numbers in a given range

Secondary Nav

C# Sharp Recursion : Exercise-6 with Solution

Write a program in C to print even or odd numbers in a given range using recursion.
Test Data :
Input the range to print starting from 1 : 20
Expected Output
:
All even numbers from 1 to 20 are :
2 4 6 8 10 12 14 16 18 20

All odd numbers from 1 to 20 are :
1 3 5 7 9 11 13 15 17 19

C# Sharp Code:

using System;

    class RecExercise6
    {
        public static void Main()
        {
    int n;
	Console.Write("\n\n Recursion : Print even or odd numbers in a given range :\n");
	Console.Write("-------------------------------------------------------------\n");	
     
    Console.Write(" Input the range to print starting from 1 : ");
    n = Convert.ToInt32(Console.ReadLine());
     
    Console.WriteLine("\n All even numbers from 1 to {0} are : ", n);
    EvenAndOdd(2, n);//call the function EvenAndOdd for even numbers 
     
    Console.WriteLine("\n\n All odd numbers from 1 to {0} are : ", n);
    EvenAndOdd(1, n);// call the function EvenAndOdd for odd numbers
    Console.WriteLine("\n\n");
     
    return ;
}
static void EvenAndOdd(int stVal, int n)
{
    if(stVal > n)
        return ;
    Console.Write(" {0}  ", stVal);
    EvenAndOdd(stVal+2, n);//calling the function EvenAndOdd itself recursively
}
}

C# Sharp Practice online:


using System;

    class RecExercise6
    {
        public static void Main()
        {
    int n;
	Console.Write("\n\n Recursion : Print even or odd numbers in a given range :\n");
	Console.Write("-------------------------------------------------------------\n");	
     
    Console.Write(" Input the range to print starting from 1 : ");
    n = Convert.ToInt32(Console.ReadLine());
     
    Console.WriteLine("\n All even numbers from 1 to {0} are : ", n);
    EvenAndOdd(2, n);//call the function EvenAndOdd for even numbers 
     
    Console.WriteLine("\n\n All odd numbers from 1 to {0} are : ", n);
    EvenAndOdd(1, n);// call the function EvenAndOdd for odd numbers
    Console.WriteLine("\n\n");
     
    return ;
}
static void EvenAndOdd(int stVal, int n)
{
    if(stVal > n)
        return ;
    Console.Write(" {0}  ", stVal);
    EvenAndOdd(stVal+2, n);//calling the function EvenAndOdd itself recursively
}
}

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables