In: Computer Science
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prime_Numbers
{
class Program
{
static void Main(string[] args)
{
int limit; // Declare limit as an int as we do not need
double.
Console.WriteLine("*****************************\nPRIME NUMBERS UP
TO 25\n*****************************");
Console.Write("Enter a limit to the prime numbers you want
displayed: ");
while (true)
{
string input = Console.ReadLine(); // Convert number to a
string.
Int32.TryParse(input, out limit);
if (!Int32.TryParse(input, out limit)) // See if we can parse the
'text' string. If False:
{
Console.WriteLine("Input must be a whole number. Please try
again.");
}
else if (limit <= 70 && limit >= 2) // If True run
the program:
{
Console.WriteLine("Calculating...");
for (int i = 1; i <= limit; i++) // Main loop for the prime
number rows.
{
if (checkPrime(i))
{
for (int j = 0; j < i; j++) //For space after "X" has
printed.
{
Console.Write("*");
}
Console.WriteLine(" " + i); // Adds prime number onto string
output.
}
}
break;
}
else // If the number is out of range:
{
Console.WriteLine("The value entered must be between 2 and
70.");
}
}
Console.ReadKey();
}
static bool checkPrime(int n) // Create function to check for prime
values.
{
// Check if n is 0 or 1.
if (n == 0 || n == 1)
{
return false;
}
else
{
// Loop from 2 to n / 2,
for (int i = 2; i <= n / 2; i++)
{
// If any number is divisible by i then it is not a prime
number
// Assign the result of a boolean expression to n.
if (n % i == 0)
{
return false;
}
}
return true;
} //end of else
}
}
}
output
If you have any query regarding the code
please ask me in the comment i am here for help you. Please do not
direct thumbs down just ask if you have any query. And if you like
my work then please appreciates with up vote. Thank You.