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

Answer:

using System;

namespace Prime
{
    class Program
    {
        // Function to check whether a number is prime
        static bool IsPrime(int num)
        {
            if (num <= 1)  // 1 and negative numbers are not prime
                return false;

            for (int i = 2; i <= Math.Sqrt(num); i++)
            {
                if (num % i == 0)  // If divisible by any number, it's not prime
                    return false;
            }
            return true;  // Prime number
        }

        static void Main(string[] args)
        {
            int num;

            // Taking input from the user
            Console.WriteLine("Enter a number: ");
            num = Convert.ToInt32(Console.ReadLine());

            // Checking if the number is prime
            if (IsPrime(num))
            {
                Console.WriteLine(num + " is a prime number.");
            }
            else
            {
                Console.WriteLine(num + " is not a prime number.");
            }
            Console.ReadLine();
        }
    }
}
Scroll to Top