G
G
G3ntl3m3n2017-04-27 21:30:09
Programming
G3ntl3m3n, 2017-04-27 21:30:09

C# how to make an array with changing values?

In general, it is necessary that the elements in the array change places, standing in odd places, with even ones. If possible, with comments. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FreeBa, 2017-04-27
@G3ntl3m3n

Something like this:

var array = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            Console.WriteLine(string.Join(" ", array));

            var last = array.Last();    //берем последний элемент
            array.Remove(last);         //удаляем его
            array.Insert(0, last);      //и добавляем в начало, все элементы сдвигаются и, соответственно, меняют четность позиции

            Console.WriteLine(string.Join(" ", array));

Or like this:
var array = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            Console.WriteLine(string.Join(" ", array));

            for (int i = 0; i < array.Count - 1; i += 2)
            {
                //Меняем соседние элементы местами
                array[i] ^= array[i + 1];
                array[i + 1] ^= array[i];
                array[i] ^= array[i + 1];
            }

            Console.WriteLine(string.Join(" ", array));

A
andoral, 2017-04-27
@andoral

int[] arr = любой массив интов;
for(int i = 0; i < arr.length - 1; i+2)
{
    int x = arr[i];
    arr[i] = arr[i+1];
    arr[i+1] = x;
}

We take a number from the array, swap it with a neighbor, move the index by 2 positions (i.e. to the next pair)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question