w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Function : To check a number is prime or not

C# Sharp Function: Exercise-9 with Solution

Write a program in C# Sharp to create a function to check whether a number is prime or not.

Pictorial Presentation:

C# Sharp Exercises: Function : To check a number is prime or not

Sample Solution:

C# Sharp Code:

using System;
public class funcexer9
{
    public static bool chkprime(int num)
    {
        for (int i=2; i < num; i++)
          if (num %i == 0) 
            return false;
        return true;
    }
    public static void Main()
    {
	  Console.Write("\n\nFunction : To check a number is prime or not :\n");
      Console.Write("--------------------------------------------------\n");
	  Console.Write("Input a number : ");
      int n= Convert.ToInt32(Console.ReadLine());	
	
        if (chkprime(n))
          Console.WriteLine(n+" is a prime number");
        else
          Console.WriteLine(n+" is not a prime number");
    }
}

Sample Output:

Function : To check a number is prime or not :                                                                
--------------------------------------------------                                                            
Input a number : 23                                                                                           
23 is a prime number

Flowchart :

Flowchart: C# Sharp Exercises - Function : To check a number is prime or not

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a program in C# Sharp to create a function to display the n number Fibonacci sequence.
Next: Write a program in C# Sharp to create a function to calculate the sum of the individual digits of a given number.

What is the difficulty level of this exercise?



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