//I want to fill an array with the first 15 prime numbers. the loop will only increase as you find the prime number and add it to the array.
int[] primes = new int[15];
int j = 0;
int i = 2;
while (j < 15)
{
if (IsPrime(i))
{
primes[j] = i;
j++;
}
i++;
}
for (int a = 0; a < primes.Length; a++)
{
Console.Write(primes[a] + " ");
}
}
//method
static bool IsPrime(int number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return true;
}
}
return false;
}
>Solution :
Problem is that your IsPrime function is actually doing the exact oposite of what you want to achieve. Look at that function again and think about where the mistake is (hint: it is a minor problem, I feel like you just overlooked something and that the logic in your mind was correct).
After you get the result you want, I also recommend you to think about IsPrime function again and try to optimize it a little bit (hint: do you really need to test all the numbers, one by one?) and also to your while loop (hint: do you really need to iterate i by 1?).
Also welcome to Stackoverflow!