How To Check If Number Is Prime Or Not In C#


In this article, I am going to discuss how to check if the number is prime or not-prime in C# with number is a number that is greater than 1 and divided by 1 or itself.

Example with C# 

Now create a new Console application and add the below code in the program.cs file.

using System;

namespace CheckPrimeInCshap
    class Program
        static void Main(string[] args)
            Console.Write("Check whether a given number is prime or not:\n");
            Console.Write("Enter a Number : ");          
            int num = int.Parse(Console.ReadLine());

            bool IsPrime = true;

            for (int i = 2; i < num / 2; i++)
                if (num % i == 0)
                    IsPrime = false;
                Console.Write(num + " is Prime Number!");
                Console.Write(num + " is not Prime Number!");


  • isPrime is used to check if a given number is prime or not. It returns true if it is prime, else false. We can check up to number/2 if anyone can divide the number or not. It makes the for loop smaller.
  • It is asking the user to enter a number to check. Using ReadLine(), it reads that number and store it in num.
  • Using isPrime, it checks if it is prime or not.
  • Based on the return value of isPrime, it prints one message.

Output 1 :

Output 2 : 

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories