### Program to Check a Number is Prime Number

Kailash Chandra Behera | Friday, June 14, 2024

### Introduction

A number is said to be prime number if that number is greater than one and can only be divided by 1 or itself. For example, 2, 3, 5 and 7 etc are prime numbers. Here in this blog, we will see how to write a program in C# to check whether a number is prime number or not.

### Getting Started

The below code example is written in the console application which describes how to check a given number is a prime number or not.

`````` static void Main(string[] args)
{
Console.Write("Enter a Number : ");
bool IsPrime = true;
for (int i = 2; i < number / 2; i++)
{
if (number % i == 0)
{
IsPrime = false;
break;
}
}
if (IsPrime)
{
Console.Write("{0} is a Prime Number.",number);
}
else
{
Console.Write("{0} is not a Prime Number.",number);
}
}
``````

## Prime Number

Output-1
`````` Enter Number: 87
87 is not a Prime Number
``````
Output-2
`````` Enter Number: 57
57 is a Prime Number
``````

In the above code snippet first, it assigns the entered number to a variable then loops using for loop Clouse, the loop starts from number two and will iterate till half of the entered number. During loop it also checks the number for prime number, If the entered number is divided by any of the iterator value, then the number is a prime number otherwise is not a prime number

## Find the Prime Number from the given Interval

The following code example takes two numbers a argument and find the prime numbers available between the two numbers.

`````` static void Main(string[] args)
{
Console.Write("Enter the start number: ");
Console.Write("Enter the end number: ");
Console.WriteLine("The prime number/s of given range");
for (int i = number1; i <= number2; i++)
{
int counter = 0;
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
counter++;
break;
}
}
if (counter == 0 && i != 1)
{
Console.WriteLine(i);
}
}
}
``````
Output
`````` Enter the start number: 1
Enter the end number: 50
The prime number/s of given range
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
``````

Thanks