For a school assignment, I need to write a program where a user types two integers (which represents indexes) and then a method generates random numbers between those two numbers. For example: if a user types 3 and 8 and array length is 15 then a method will generate random numbers between index 3 and index 8 in an array. I'm trying something like this but it's not working:
int[] arry = new int[15];
int b = int.Parse(Console.ReadLine());
int a = int.Parse(Console.ReadLine());
Filling(a, b, arry);
static void Filling(int a, int b, int[] arry)
{
Random rnd = new Random();
for (int i = arry[a]; i < arry[b]; i )
{
arry[i] = rnd.Next(3, 31);
Console.WriteLine(arry[i]);
}
}
CodePudding user response:
As mentioned in the comments, you want the loop to iterate between a
and b
. Not between the values stored in the array for a and b. i.e.
for (int i = a; i < b; i )
{
arry[i] = rnd.Next(3, 31);
Console.WriteLine(arry[i]);
}
You might also want to add some bounds-checking to ensure that a and b are valid. This can be done by clamping the index values before entering the loop.
a = Math.Max(a, 0);
b = Math.Min(b, arry.Count);