Do you want to find prime numbers between 1 to 100 in C#? In this C# tutorial, I will explain how to find prime numbers from 1 to 100 in C#.
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. For example, 5 is a prime number because the only way to create it is by multiplying 1 by 5.
Find Prime Numbers From 1 To 100 In C#
Here is a simple yet effective way to find all the prime numbers from 1 to 100 in C#:
using System;
class PrimeNumbers
{
static void Main()
{
Console.WriteLine("Prime numbers between 1 and 100 are:");
for (int i = 1; i <= 100; i++)
{
if (IsPrime(i))
{
Console.WriteLine(i);
}
}
}
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;
}
}
IsPrime
Function: This function takes an integer as input and returnstrue
if it’s a prime number andfalse
otherwise. It first checks if the number is less than 2 or an even number (other than 2). It then checks for divisibility by odd numbers up to the square root of the number.Main
Method: This is the entry point of the program. It uses a for loop to check each number from 1 to 100 by calling theIsPrime
function.
You can check in the screenshot below where I ran the code using the C# Windows console application.
Conclusion
In this C# tutorial, I will explain how to find prime numbers from 1 to 100 in C#. I have explained, how to write a c# program to print all the prime numbers between 1 to 100.
You may also like:
- Write A C# Program To Find The Largest Of Three Numbers
- Write A Program To Find Second Largest Number In An Array In C#
- How to Write a Program to Find a Leap Year in C#
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…