C# Program to check a number is prime or not


In this program, You will learn how to check a number is prime or not in C#.


Some list of prime numbers is: 2, 3, 5, 7, 11

Example: How to check a number is prime or not in C#.

using System;
public class Program
{
	public static void Main(string[] args)
	{
		int n, i = 2, p = 1;

		Console.Write("Enter a number:");
		n = Convert.ToInt32(Console.ReadLine());

		while (i < n)
		{
			if (n % i == 0)
			{
				p = 0;
				break;
			}
			i++;
		}

		if (p == 1)
		{
			Console.WriteLine("Number is prime:" + n);
		}
		else
		{
			Console.WriteLine("Number is not prime:" + n);
		}
	}
}

Output:

Enter a number:17
Number is prime:17