Frage

Hi I wrote a method/array I am trying to make my code swap the second number and second to last number in the index but the only number that's is swapping was my second number and my last, if you could help a newbie I would be very thank full.

static void Main(string[] args)
{
    Console.WriteLine("\n=====================\n");
    DisplayArray(A); 
    Console.WriteLine("\nSwapping Second and Second to last Number");
    SwapSecAndSecLast(A);
    DisplayArray(A);

    Console.ReadLine();
}

static void SwapSecAndSecLast(int[] array)
{
    int temp = array[1];
    array[1] = array[array.Length - 1];
    array[array.Length - 1] = temp;
}

static void DisplayArray(int[] array)
{
    Console.WriteLine("\n=====================\n");
    for (int i = 0; i < array.Length; i++)
    {
        Console.Write("{0} ",array[i]);
    }
    Console.WriteLine("\n=====================\n");
}
War es hilfreich?

Lösung

The second to last is

array[array.Length - 2];

not

array[array.Length - 1];

... since arrays are zero-based. However, you should check if it contains enough elements.

Andere Tipps

Arrays are 0 based, so array[array.Length - 1] is the last element in the array. If you want the second to last, use array[array.Length - 2]

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top