Program to Display Prime Numbers Between Intervals Using Function - (C# Basic Programs)
Finding prime numbers is a common programming exercise that helps improve problem-solving skills. In this tutorial, we will discuss a program to display prime numbers between two intervals using a function in the C# programming language.
Syntax
The syntax for finding prime numbers in C# can be defined using the following code structure:
public static bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var boundary = (int)Math.Floor(Math.Sqrt(number));
for (int i = 3; i <= boundary; i += 2)
if (number % i == 0)
return false;
return true;
}
Example
using System;
class Program
{
static void Main(string[] args)
{
int start, end;
Console.Write("Enter the start of range: ");
start = int.Parse(Console.ReadLine());
Console.Write("Enter the end of range: ");
end = int.Parse(Console.ReadLine());
Console.WriteLine("Prime numbers between {0} and {1} are: ", start, end);
for (int i = start; i <= end; i++)
{
if (IsPrime(i))
{
Console.Write(i + " ");
}
}
Console.ReadLine();
}
public static bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
var boundary = (int)Math.Floor(Math.Sqrt(number));
for (int i = 3; i <= boundary; i += 2)
if (number % i == 0)
return false;
return true;
}
}
Output:
Enter the start of range: 1
Enter the end of range: 20
Prime numbers between 1 and 20 are:
2 3 5 7 11 13 17 19
Explanation
The program creates a function called IsPrime()
that takes a number and returns a boolean indicating whether the number is prime or not. The function is then used in a loop to check each number in the user-specified range. If a number is prime, it is added to the output.
Use
This program is used to display prime numbers between two intervals using a function in the C# programming language. It is used to improve problem-solving skills and develop a better understanding of functions, loops, and conditionals.
Summary
In this tutorial, we discussed a program to display prime numbers between two intervals using a function in the C# programming language. We covered the syntax, example, output, explanation, and use of finding prime numbers in C#. By practicing these exercises, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges related to prime numbers.