Write a program in C# to print even or odd numbers in a given range using recursion

  • برمجة سي شارب
  • برمجة

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

الأجوبة

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
}
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...