w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Check a number is prime number or not

Secondary Nav

C# Sharp Recursion : Exercise-7 with Solution

Write a program in C# Sharp to check whether a number is prime or not using recursion.
Test Data :
Input any positive number : 37
Expected Output
:
The number 37 is a prime number.

C# Sharp Code:

using System;

    class RecExercise7
    {
        public static int Main()
        {
    int n1,primeNo;

	Console.WriteLine("\n\n Recursion : Check a number is prime number or not :");
	Console.WriteLine("--------------------------------------------------------");
	
    Console.Write(" Input any positive number : ");
    n1 = Convert.ToInt32(Console.ReadLine());

    primeNo = checkForPrime(n1,n1/2);//call the function checkForPrime

   if(primeNo==1)
        Console.Write(" The number {0} is a prime number. \n\n",n1);
   else
      Console.WriteLine(" The number {0} is not a prime number. \n\n",n1);
   return 0;
}

static int checkForPrime(int n1,int i)
{
    if(i==1)
    {
        return 1;
    }
    else
    {
       if(n1 %i==0)
         return 0;
       else
         return checkForPrime(n1,i-1);//calling the function checkForPrime itself recursively
    }
  }
}

C# Sharp Practice online:


using System;

    class RecExercise7
    {
        public static int Main()
        {
    int n1,primeNo;

	Console.WriteLine("\n\n Recursion : Check a number is prime number or not :");
	Console.WriteLine("--------------------------------------------------------");
	
    Console.Write(" Input any positive number : ");
    n1 = Convert.ToInt32(Console.ReadLine());

    primeNo = checkForPrime(n1,n1/2);//call the function checkForPrime

   if(primeNo==1)
        Console.Write(" The number {0} is a prime number. \n\n",n1);
   else
      Console.WriteLine(" The number {0} is not a prime number. \n\n",n1);
   return 0;
}

static int checkForPrime(int n1,int i)
{
    if(i==1)
    {
        return 1;
    }
    else
    {
       if(n1 %i==0)
         return 0;
       else
         return checkForPrime(n1,i-1);//calling the function checkForPrime itself recursively
    }
  }
}

Improve this sample solution and post your code through Disqus



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

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program