C# Program to check a number is prime or not using class


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


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

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

using System;
public class Program
{
	public int check(int n)
	{
		int i = 2, p = 1;

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

	public static void Main(string[] args)
	{
		int x, res;

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

		Program obj = new Program();
		res = obj.check(x);

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

Output:

Enter a number:13
Number is prime:13