csharp program to find n prime numbers in c# dotnet

Prime number program in csharp: c# program for prime number

  • The following code code prints prime numbers using csharp .net programming language. 
  • Logic for Primer Number is shown below in the code snippet with output: 
  • A number is prime if it is divisible only by one and itself. 
  • Number two is the only even and also the smallest prime number. 
  • Some example prime numbers are 2, 3, 5, 7, 11, 13, 17....etc. 
  • Every student learning programming in csharp .net will definately have to write the basic program to find prime numbers as it helps to develop the logical mind needed for programming
  • The following program will ask you to enter a number 
  • After taking the input number it will display the number of prime numbers
  • if you enter 10 the program will show the first 10 prime numbers
Prime Number Code:
 
 using System;

 namespace primerNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, i = 3, count, c;

            Console.WriteLine("Enter the number of prime numbers you want");
            num =Convert.ToInt32( Console.ReadLine());

            if (num >= 1)
            {
               
                Console.WriteLine("First "+num+" Prime Numbers are :\n");
                Console.WriteLine("2");
            }

            for (count = 2; count <= num; )
            {
                for (c = 2; c <= i - 1; c++)
                {
                    if (i % c == 0)
                        break;
                }
                if (c == i)
                {
                    Console.WriteLine("\n"+i);
                    count++;
                }
                i++;
            }
        }
    }
}



After writing this program hit F5 or cltr+F5 .
you will see a black window .program running 
Output:- 
Enter the number of prime numbers you want
5
First 5 Prime Numbers are:

3
5
7
11
Live Demo:

4 comments: