How to reverse an array in C#
The Array class in the System namespace provides the Reverse() method
Syntax
public static void Reverse (Array array);
- This method works only for single dimensional
Arraysand throws aRankExceptionif thearraypassed as input is multi-dimensional. - It throws a
ArgumentNullExceptionif the input array is null. - The
Reverse()method does not use an auxiliary array for reversal and overwrite the existing elements of the array. - The time complexity of
Array.Reverse()method isO(n), wherenis the number of elements in the array.
In the example below, we have created and initialized an Array with integers. We then print the Array elements before calling the Reverse() method.
We then call the Reverse() method and print the Array contents again.
The array elements are now reversed, so the program prints the following output.
Array Initial State: 11,12,13,14,15,16,17
Array After Reversal: 17,16,15,14,13,12,11
Code
using System;class HelloWorld{static void Main(){int[] inputArray = new int[]{11,12,13,14,15,16,17};Console.WriteLine("Array Initial State: {0}",string.Join(",",inputArray));Array.Reverse(inputArray);Console.WriteLine("Array After Reversal: {0}",string.Join(",",inputArray));}}