Reputation: 97
I'm learning C# and I have created a code to add random numbers to a List
using a for
loop.
class Program
{
static void Main(string[] args)
{
Random numberGen = new Random();
List<int> randomNum = new List<int>();
for (int i = 0; i < 10; i++)
{
randomNum.Add(numberGen.Next(1, 100));
}
for (int i = 0; i < randomNum.Count; i++)
{
Console.WriteLine(randomNum[i]);
}
Console.ReadKey();
}
}
I want to know if there is a way to add random numbers to an array with a similar method?
Upvotes: 2
Views: 924
Reputation: 32780
Use a List<T>
, thats is the scenario it was precisely designed for. Once you've finished adding elements to it, if you need an array then simply call ToArray()
:
var myList = new List<int>();
//add random number of random numbers
var myArray = myList.ToArray();
Upvotes: 0
Reputation: 312136
You could just assign to the relevant index directly, but note you'll have to initialize the array to the required size (as opposed to a List
that can grow dynamically):
int[] randomNum = new int[10];
for (int i = 0; i < randomNum.Length; i++)
{
randomNum[i] = numberGen.Next(1, 100);
}
Upvotes: 1
Reputation: 1063994
The size of an array is fixed at the time of creation, so you can't add to an array; you can, however: create a new array that is bigger, copy the old data, and then append the new value(s) - Array.Resize
does the first two steps - but: this is pretty expensive, which is why you usually use a List<T>
or similar for this scenario. A List<T>
maintains an oversized array in the background, so that it only has to resize and copy the underlying array occasionally (essentially, it doubles the size every time it gets full, so you get something approximating O(Log2(N))
overhead due to growth).
Upvotes: 5