There was a problem, please help me solve it with "system.indexoutofrangeexception". An error occurs here:

Console.WriteLine("Массив с нечетного ряда чисел: "); for (i = 0; i < 30; i++) Console.Write(" {0}", b[i]); (ЗДЕСЬ!) Console.ReadLine(); 

Help please solve. It is necessary that from the initial array only those digits remain that stand in odd places (1,3,5,7,9 etc)

 using System; namespace tapsyrma { class Program { static void Main(string[] args) { int i, k,y=0; int[] a = new int[30]; int[] b = new int[(a.Length + 1) / 2]; Random rnd = new Random(); Console.WriteLine("Исходный массив: "); for (i = 0; i < 30; i++) { a[i] = rnd.Next(-50, 51); Console.Write(" {0}", a[i]); } for (i = 0; i <30; i++) { if (a[i] % 2 != 0) y++; } Console.WriteLine(); for (i = 0, k = 0; i < b.Length; i++, k+=2) { b[i] = a[k]; } Console.WriteLine("Массив с нечетного ряда чисел: "); for (i = 0; i < 30; i++) Console.Write(" {0}", b[i]); Console.ReadLine(); } } } 
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Your array b defined as

 int[] b = new int[(a.Length + 1) / 2]; 

that is, it has 15 elements as defined by array a

 int[] a = new int[30]; 

However, in this cycle

  for (i = 0; i < 30; i++) Console.Write(" {0}", b[i]); 

You are using an index outside the allowable range of indices for array b .

At least you could write

  for (i = 0; i < b.Length; i++) Console.Write(" {0}", b[i]); 

Keep in mind that in the conditions of the assignment you wrote that

It is necessary that only the digits from the original array remain on odd places.

and in this cycle

  for (i = 0; i <30; i++) { if (a[i] % 2 != 0) y++; } 

calculate how many elements of the array have even values. In this case, the variable y not used anywhere else.