In this example , I’ll show you How to print out the first 50 prime numbers. Start with a while loop, probably.
Example 1:
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
static void Main(string[] args) { int num = 2; int counter1 = 0; int counter2 = 0; int counter3 = 0; Console.WriteLine("First 50 Prime Numbers"); Console.WriteLine("=================="); while (true) { counter1 = 0; if (counter2==50) { break; } for (int i = 2; i < num; i++) { if(num % i == 0) { counter1++; break; } } if(counter1==0) { counter3++; Console.Write(num+"\t"); if (counter3%10==0) { Console.WriteLine(); } counter2++; } num++; } Console.ReadKey(); } |
Example2 :
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
static void Main(string[] args) { int ct = 0, n = 0, i = 1, j = 1; while (n < 50) { j = 1; ct = 0; while (j <= i) { if (i % j == 0) ct++; j++; } if (ct == 2) { Console.Write(i); Console.Write(" "); n++; } i++; } Console.ReadKey(); } |