blah blah blah is here! blah blah » Close

up0down
link

write a program in c# to display prime numbers till the number entered by user.

please help me for this program.

last answered one year ago

1 answers

up0down
link

Well, this is obviously a homework question but, as it's very easy, I'll do it for you just this one time.

If you need any help with future questions, please have a go at it yourself first, post your code and tell us what difficulty you're having.

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
class Program
{
static void Main()
{
List<int> primes = new List<int>();
primes.Add(2);
Console.Write("Calculate primes up to : ");
int n = int.Parse(Console.ReadLine());
bool isPrime = true;

for (int i = 3; i <= n; i += 2) // can't be prime if even number > 2
{
for (int j = 0; j < primes.Count; j++)
{
if (i % primes[j] == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
primes.Add(i);
}
else
{
isPrime = true;
}
}

// print them out
Console.WriteLine();
foreach (int prime in primes) Console.Write("{0,3} ", prime);
Console.WriteLine();
Console.ReadKey();
}
}
}

Feedback