I am trying to make a method to modify an array, I do not know why it does not work?
When I said int[] arr = array
, I want to do this so that it is not affected, so I can use elements for the second cycle for
, 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 as I started with array.Length-1
, it must begin with the last element, and it should be array[5]=arr[6-1-5]
, that should be array[5]=arr[0]
and arr[0]
is equal to 1, but I think it is obtained as 6, why?
Here is the complete code:
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;
}
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();
}
source
share