I'm trying to reverse an array. This is my code:
using System;
class Hello
{
static void Main()
{
int[] num = new int[] { 1, 2, 3, 4, 5 };
int index = num.Length - 1;
int[] newNum = new int[index];
for (int i = 0; i < num.Length; i++)
{
newNum[i] = num[index]; // error
index--;
Console.WriteLine(newNum[i]);
}
Console.ReadLine();
}
}
When I run the code, the console prints
5
4
3
2
and then returns an error:
IndexOutOfRangeException was unhandled
on the line:
newNum[i] = num[index];
What's wrong with that line of code? When I print num[0]
before that for loop it works fine.