Below is a program in C# that check whether a number is prime or not. The program inputs a value form the user and print whether it is prime or not.

What is a prime number?

Every number is a prime number or a composite number except 0 and 1. A prime number is a number which is divisible only by itself.

Here are some first few prime numbers 2, 3, 5, 7, 11, 13, 17, 19, and 23.

Program Source Code

Here is the source code of the program to check whether a number is prime or not in C#. This program is successfully compiled, and the output is also given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrimeNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            int count = 0;
            Console.Write("Enter a number to check if number is prime or not :");
            num = int.Parse(Console.ReadLine());
            if(num <= 1)
            {
                Console.WriteLine("\nInvalid number please Try Again");
            }
            for(int i = 2; i < num/2; i++)
            {
                if(num % i == 0)
                {
                    count = 1;
                    break;
                }
            }
            if(count==1)
            {
                Console.WriteLine("\nEntered Number is Not Prime");
            }
            else
            {
                Console.WriteLine("\nEntered Number is Prime");
            }
            Console.ReadLine();
        }
    }
}

Result

Result

Program Explanation

C# program starts execution from the main method. We declared a num variable to input a number form the user to check whether it is prime or not. After inputting a number from the user, if-statement is used.

If the entered number is less than or equal to 1, then the error message will be shown. For-loop is used to check if the number is prime. Inside the for-loop, anif-else statement is used. If the modulus of the num variable is equal to 0, then the number is not prime. Else the number is prime will be printed on the screen.

Related Articles

Last modified: May 19, 2019

Comments

Write a Reply or Comment

Your email address will not be published.