In .Net Framework reversing array elements can be done by using Reverse method on Array type. This code snippet shows you how this method can be used to reverse an array.

// Declare an array with 10 elementsint[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };// Output elements in original orderfor (int i = 0; i < numbers.Length; i++){ Console.Write(" {0}", numbers[i]);}Console.WriteLine();// Reverse the arrayArray.Reverse(numbers);// Output elements with changed orderfor (int i = 0; i < numbers.Length; i++){ Console.Write(" {0}", numbers[i]);}Console.ReadKey();

Here is the output.

image

Array.Reverse method also provides an overload which can be used to reverse elements at a given indexes. For example we want to reverse elements 3, 4 and 5 but leave others intact. This can be achieved using the following code snippet.

// Declare an array with 10 elementsint[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };// Output elements in original orderfor (int i = 0; i < numbers.Length; i++){ Console.Write(" {0}", numbers[i]);}Console.WriteLine();// Reverse numbers 3 , 4 and 5Array.Reverse(numbers, 2, 3);// Output elements with changed orderfor (int i = 0; i < numbers.Length; i++){ Console.Write(" {0}", numbers[i]);}Console.ReadKey();

And the output is.

image

Tagged with:
 

5 Responses to Reverse Array Elements Using C#

  1. Lee Joseph says:

    Hi there, I understand on how to reverse the array. But how can you Rearrange the numbers in the array so that the first becomes the last, etc.
    I can understand you can physically swap each array around but what if you let the user to choose how big the array is going to be.
    cheers
    Lee

  2. Lee Joseph says:

    In order to cmplete this, can I cahnge the for loop to assign the first entered numbers to the end of the array, thus automatically reversing the entered numbers? if so how do I do this?

  3. Lee Joseph says:

    I have managed to do it now. Basically I have reversed the original array then copied it to a newly created array then used for each to show the new array thus swapping all of the values around so the last original value is now the 1 st value

  4. Deepak says:

    Hi Lee,

    Sorry if I misunderstood but isn’t that what Array.Reverse is doing?

  5. Lee Joseph says:

    it is yeah, but my lecturer wanted us to read in numbers
    and then reverse them without using Array.reverse and permemently keeping them in the reverse order in the array.

    He wasnt happy with the way I have done it by creating a new aray, soI’ve had to do it all over again

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>