w3resource
C# Sharp Programming Exercises

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

C# Sharp Recursion : Exercise-6 with Solution

Calculating a Even Numbers:

Calculating a Even Numbers

Even Numbers between 1 to 100:

Even Numbers between 1 to 100

Calculating a Odd Numbers:

Calculating a Odd Numbers

Odd Numbers between 1 to 100:

Odd Numbers between 1 to 100

Sample Solution:-

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
}
}

Sample Output:

 Recursion : Print even or odd numbers in a given range :                                                     
-------------------------------------------------------------                                                 
 Input the range to print starting from 1 : 20                                                                
                                                                                                              
 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

Flowchart :

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

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a program in C# Sharp to count the number of digits in a number using recursion.
Next: Write a program in C# Sharp to check whether a number is prime or not using recursion.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming