Write a C# program that prints the Prime numbers between 1 and 100 and also print the count of prime numbers between 1 and 100. (Try to avoid inbuild functions)

 Posted by Nagasundar_Tn on 11/30/2012 | Category: C# Interview questions | Views: 31350 | Points: 40
Answer:

Prime numbers are the numbers which are divisible by 1 and that number itself. Here is the code:
class Program

{
public bool IsPrimeNumber(int num)
{
bool bPrime = true;
int halfNo = num / 2;
int i = 0;

for (i = 2; i <= halfNo; i++)
{
if ((num % i) == 0)
{
bPrime = false;
break;
}
}

if (bPrime == true)
chk++;

return bPrime;
}
static void Main(string[] args)
{
Console.WriteLine("List of prime numbers between 0 to 100");
Program pObj = new Program();
for (int val = 1; val <= 100; val++)
{
if (pObj.IsPrimeNumber(val) == true)
{
Console.Write(string.Format("{0,8:n}\t", val));
}
}


Console.WriteLine(string.Format("\nTotal count " + chk));
}
}


In the above code I am creating a for loop from 1 to 100 in Main() function. Inside the for loop I am calling ISPrimeNumber method which returns boolean.

In IsPrimeNumber method I have declared bPrime variable and initialized to true. Then I am getting the half of the passed value. Because the factors will not be greater then half of the given number.


Say for example : The number is 20

then 20/2 = 10

so the for loop in IsPrimeNumber() method runs 10 times in this scenario. Here I am checking reminder for each iteration of i. i.e like (20%2, 20%3,..)

for 20 ---> 20%2 = 0 so I am using break stement to exit the for loop. Since first iteration itself satisfies the condition, no need to check the rest.

If we take 23

then 23/2 = 11.

so the for loop in IsPrimeNumber() method runs 11 times.

for 23---> 23%2 !=0,23%3 !=0,23%4 !=0,23%5 !=0,23%6 !=0,23%7 !=0,23%8 !=0,23%9 !=0,23%10 !=0,23%11 !=0. So this number is Prime number.

To get the count of prime numbers I am using "chk" variable and incremented it when prime number is encountered


The output will be:

  1.00            2.00            3.00            5.00            7.00

11.00 13.00 17.00 19.00 23.00
29.00 31.00 37.00 41.00 43.00
47.00 53.00 59.00 61.00 67.00
71.00 73.00 79.00 83.00 89.00
97.00
Total count 26


Asked In: SRA Systems | Alert Moderator 

Comments or Responses

Login to post response