TechieClues .
Updated date Feb 23, 2021
This code snippet explains how to check a number is a prime number or not in C#. A prime number is a number that is greater than 1 and divided by 1 or itself.

This code snippet explains how to check a number is a prime number or not in C#. A prime number is a number that is greater than 1 and divided by 1 or itself. For example, prime numbers are  2, 3, 5, 7, 11, 13, 17, 19, 23....

``````using System;

namespace SampleProgram
{
class PrimeExample
{
static void Main()
{
// Get input
Console.WriteLine("Enter a number:");

// Check whether the given number is prime or not
Console.WriteLine("{0} is a prime number", number);
else
Console.WriteLine("{0} is not a prime number", number);
}

// This method returns the bool value. i.e., True for prime and False for non-prime numbers
{
int x = 0;
for (int i = 1; i <= number; i++)
{
if (number % i == 0)
{
x++;
}
}
if (x == 2)
{
return true;
}
return false;
}
}
}``````

Output 1:

``````Enter a number:
2
2 is a prime number``````

Output 2:

``````Enter a number:
8
8 is not a prime number``````

TechieClues .
Software Professional, India

IT professional with 15+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m