In this C# program, we will learn how to write a program to check the given number is prime or not.
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers and divided by 1 or itself. In other words, prime numbers can't be divided by other numbers than itself or 1.
For example, 7 is prime because the only ways of writing it as a product, 1 × 7 or 7 × 1, involve 7 itself.
Here is the code of the program to check the given number is prime or not:
using System;
namespace TutorialsrackPrograms
{
class Program
{
//C# Program to Check Given Number is Prime or Not.
static void Main(string[] args)
{
Console.Write("Enter any number: ");
int number = Convert.ToInt32(Console.ReadLine());
int x = 0;
for (int i = 1; i <= number; i++)
{
if (number % i == 0)
{
x++;
}
}
if (x== 2)
{
Console.WriteLine("{0} is a Prime Number", number);
}
else
{
Console.WriteLine("{0} is not a Prime Number",number);
}
Console.Read();
}
}
}
First Output when Input is 7
Enter any number: 7
7 is a Prime Number
First Output when Input is 10
Enter any number: 10
10 is not a Prime Number
Comments