C# Program to print all prime numbers between 1 to n
In this program, You will learn how to print all prime numbers between 1 to n in C#.
Some list of prime numbers is: 2, 3, 5, 7, 11
Example: How to print all prime numbers between 1 to n in C#.
using System;
public class Program
{
public static void Main(string[] args)
{
int n, i, p, k;
Console.Write("Enter a number:");
n = Convert.ToInt32(Console.ReadLine());
for (i = 2; i <= n; i++)
{
k = 2;
p = 1;
while (k < i)
{
if (i % k == 0)
{
p = 0;
break;
}
k++;
}
if (p == 1)
{
Console.WriteLine("Number is prime:" + i);
}
}
}
}
Output:
Enter a number:50
Number is prime:2
Number is prime:3
Number is prime:5
Number is prime:7
Number is prime:11
Number is prime:13
Number is prime:17
Number is prime:19
Number is prime:23
Number is prime:29
Number is prime:31
Number is prime:37
Number is prime:41
Number is prime:43
Number is prime:47