C# Sharp Exercises: Print even or odd numbers in a given range
C# Sharp Recursion : Exercise-6 with Solution
Write a program in C# Sharp to print even or odd numbers in a given range using recursion.
Calculating a Even Numbers:
Even Numbers between 1 to 100:
Calculating a Odd Numbers:
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 :
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?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework