0

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
ALH
  • 85
  • 4
  • 14

1 Answers1

0

length of your new array is 4. that's mean I'll cover from 0 to 3

int[] newNum = new int[index];

and your loop will go i=4

when i will 4 your code will collapse. as newNum support only to 3rd index.

this should be

int[] newNum = new int[index+1];
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80