How to Print Prime Numbers in C#?
Aug 19, 2019
C#,
2467 Views
Program to display the prime number in a given range
Prime Number
Let's create a program to display the prime number in a given range:
using System;
public class PrimeNo
{
public static void Main()
{
int count,low,high;
Console.Write("Enter the lower range: ");
low = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the upper range: ");
high = Convert.ToInt32(Console.ReadLine());
Console.Write("The prime numbers between {0} and {1} are : ",low,high);
for(int num = low;num<=high;num++)
{
count = 0;
for(int i=2;i<=num/2;i++)
{
if(num%i==0){
count++;
break;
}
}
if(count==0 && num!= 1)
Console.Write("{0} ",num);
}
Console.Write("\n");
}
}
Output:
Enter the lower range: 5
Enter the upper range: 50
The prime numbers between 5 and 50 are : 5 7 11 13 17 19 23 29 31 37 41 43 47
Parameters used in the Program
- using System: It is a namespace which contains the commonly used types. It is specified with a using System directive.
- class PrimeNo: class is the keyword which is used for the declaration of classes.
- public static void Main(string[] args): Here public keyword sates that it is accessible to all. static keyword tells us that this method is accessible without instantiating the class. void keyword tells that this method will not return anything. Main() method is the entry point of our application.
- Console.WriteLine(): WriteLine() is a method of the Console class defined in the System namespace.