In Interview its a common question for fresher as well as experience to do code to check given number is prime or not. No matter in which language you written the code but matter is what logic you follow to do this. I hope you all aware about what is prime number if no then let me explain what is prime number

Prime number is a number which is divisible by same number and only by 1. Lets take an example

Suppose we take a number 6. Is it prime number ?

No due to its divisible by 2 & 3 also.

Lets take an another example is 23 is prime number

Yes because its divisible by 1 & 23 only.

Lets Implement these in programming language

using System;

namespace example

{

public class CheckPrime

{

public static void Main()

{

Console.Write("Please enter a number: ");

int num;

num = Convert.ToInt32(Console.ReadLine());

int j;

j = 0;

for (int i = 1; i <= num; i++)

{

if (num % i == 0)

{

j++;

}

}

if (j == 2)

{

Console.WriteLine("Wow! Entered Number is a Prime Number");

}

else

{

Console.WriteLine("Oops! Entered Number is Not a Prime Number");

}

Console.ReadLine();

}

}

}
Please enter a number

Wow! Entered Number is a Prime Number

Prime number is a number which is divisible by same number and only by 1. Lets take an example

Suppose we take a number 6. Is it prime number ?

No due to its divisible by 2 & 3 also.

Lets take an another example is 23 is prime number

Yes because its divisible by 1 & 23 only.

Lets Implement these in programming language

### Program to check number is prime or not in C#

namespace example

{

public class CheckPrime

{

public static void Main()

{

Console.Write("Please enter a number: ");

int num;

num = Convert.ToInt32(Console.ReadLine());

int j;

j = 0;

for (int i = 1; i <= num; i++)

{

if (num % i == 0)

{

j++;

}

}

if (j == 2)

{

Console.WriteLine("Wow! Entered Number is a Prime Number");

}

else

{

Console.WriteLine("Oops! Entered Number is Not a Prime Number");

}

Console.ReadLine();

}

}

}

### Output of prime number check in C#

**23**

Wow! Entered Number is a Prime Number

This comment has been removed by a blog administrator.

ReplyDelete