I am trying to make a method to reverse an array, I don't know why it is not working?
When I said int[] arr = array, I want to do this so it will not be affected so I can use the elements for the second for loop and it should have elements {1,2,3,4,5,6} but when I use
for (int i=array.Length-1;i>array.Length/2;i--)
{
array[i] = arr[array.Length - 1 - i];
}
In this case I have 6 elements so array.Length is 6 and since I started from array.Length-1 it must start from the last element and it must be array[5]=arr[6-1-5] which must be array[5]=arr[0] and arr[0] is 1 but I think it is getting it as 6, why?
Here is the complete code:
// ReverseArray method
static int [] ReverseArray(int [] array)
{
int[] arr = array;
for (int i=0; i<array.Length/2;i++)
{
array[i] = array[array.Length-1 - i];
}
for (int i=array.Length-1;i>array.Length/2;i--)
{
array[i] = arr[array.Length - 1 - i];
}
return array;
}
// Method for displaying elements of Array
static void DisplayArray(int [] array)
{
int i;
Console.Write("{");
for (i = 0; i < array.Length-1; i++)
{
Console.Write(array[i] + ",");
}
Console.WriteLine(array[i] + "}");
}
static void Main(string[] args)
{
int[] array = { 1, 2, 3, 4, 5 ,6};
ReverseArray(array);
DisplayArray(array);
Console.ReadKey();
}