Question

I try Start the console and after i write 5 numbers is do exsepsion what wrong in code

what the console do is after I write 5 number for example 7,4,9,5,1 ---> 1,5,9,4,7

this what I wrote

    static void Main(string[] args)
    {

         int[] numbers = new int[5];

        for (int i = 0; i < numbers.Length ; i++)
        {
            Console.Write("");

            numbers[i] = int.Parse(Console.ReadLine());

        }


        for (int i = 0; i < numbers.Length / 2; i++)
        {
            int x = numbers[i];
            numbers[i] = numbers[numbers.Length - i - 1];
            numbers[numbers.Length - i - 1] = x;
        }



        Console.Read();
Was it helpful?

Solution

You missed two things. First - in order to swap two array items, you need to store item somewhere. Otherwise you just replace one item with other. Second - arrays have indexes from 0 to Length - 1. So you need to subtract 1 from second item index:

for (int i = 0; i < numbers.Length / 2; i++)
{
    int x = numbers[i];
    numbers[i] = numbers[numbers.Length - i - 1];
    numbers[numbers.Length - i - 1] = x;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top