The Program in C# Program to Determine If Given number is prime or not is given below:
using System;
namespace PrimeNumber
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, Enter a number here to check if it is a prime number: ");
int number = int.Parse(Console.ReadLine());
if (IsPrime(number))
{
Console.WriteLine(number + " is a prime number.");
}
else
{
Console.WriteLine(number + " is not a prime number.");
}
Console.ReadLine();
}
static bool IsPrime(int num)
{
if (num <= 1)
{
return false;
}
for (int i = 2; i <= Math.Sqrt(num); i++)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
}
}
Output:
Hello Codeauri Family, Enter a number here to check if it is a prime number:
7
7 is a prime number.
Pro-Tips💡
Here are the step by step execution of above program:
- The program starts by including the
System
namespace using theusing
keyword. - The code is contained within a namespace called
PrimeNumber
. This allows the code to be organized and reused easily in other projects. - The
Program
class contains the main methodMain
, which is the starting point of the program. - Within the
Main
method, the user is prompted to enter a number using theConsole.WriteLine
method. The user’s input is then converted to anint
usingint.Parse
and stored in thenumber
variable. - The
IsPrime
method is then called and passed thenumber
as an argument. The method returns abool
value, which is stored in a variableresult
. - The
Main
method checks the value ofresult
. Ifresult
istrue
, the message “The number is a prime number.” is displayed on the console. Ifresult
isfalse
, the message “The number is not a prime number.” is displayed. - The
Console.ReadLine
method is used to pause the program and wait for the user to press Enter. - The
IsPrime
method checks if the number is less than or equal to 1. If it is, the method returnsfalse
, as 1 is not a prime number and numbers less than 1 are not considered valid numbers. - The method then loops through all the numbers from 2 to the square root of the input number using a
for
loop. - Within the loop, the method checks if the input number is divisible by the current loop variable
i
by using the modulo operator%
. If it is divisible, the method returnsfalse
, as the number is not a prime number. - If the method completes the loop without finding any factors, it returns
true
as the number is a prime number.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.