This is my code:
int[] primes = new int[25];
for (int i = 2; i <= 100; i++)
{
for (int j = i; j > 0; j--)
{
int prime = i%j;
if (prime == 0)
{
if ((j == i) || (j == 1))
{
isPrime = true;
}
else
{
isPrime = false;
break;
}
}
}
if (isPrime == true){
primes[index] = i;
index++;
}
}
As you can see, I'm writing prime numbers into array. I counted all the prime numbers that are within range 2-100, so I set array size to 25.
But let's say that I wouldn't know there are 25 prime numbers. Is there a way to create an array (any type of array) without defining the size? I tried this:
int[] primes = new int[0];
But it crashed.
You can use List
for unknown size of data (probably ArrayList
will be the best solution for you).
No; an array's size must be declared ahead of time. Try taking a look at the different implementations of List
or Vector
.
If in the end you absolutely need an array, you may create an array from your List
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With