Basically I am doing a C# assignment for part of my uni course. This part of it needs to create an array with 10 items. All the items should be random numbers generated between 0 and 19. The i need to use a for loop to print out what each item is. The problem is i am getting an IndexOutOfRangeException and i have no idea why, so was just wondering if anyone could take a look at it and help me out, tanks in advance, here it is:
int MaxValue;
int RandomNumber;
Random MyRandom;
MaxValue = 20;
MyRandom = new Random();
RandomNumber = MyRandom.Next(MaxValue);
int[] firstArray = new int[9];
for (int i = 0; i < 10; i++)
{
firstArray[i] = RandomNumber;
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Item {0} in the array is {1}", i, firstArray[i]);
}
Loading
Sivaraman DhamodaranPosted Jan 21, 2013, 8:26 AM
int[] firstArray = new int[9];
Asking for only 9 rooms to hold the values.
And, you are iterating for 10 times 0,1,2,3,4,5,6,7,8,9
for (int i = 0; i < 10; i++)
{
firstArray[i] = RandomNumber;
}
Correction:
int[] firstArray = new int[10];
Jamie DalleyPosted Jan 21, 2013, 10:56 AM