Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
array
reverse
community creator

How to reverse an array in C#

Surabhi Sharma

The Array class in the System namespace provides the Reverse() methodused to reverse the elements of an array with multiple overloads.

Syntax

public static void Reverse (Array array);
  • This method works only for single dimensional Arrays and throws a RankException if the array passed as input is multi-dimensional.
  • It throws a ArgumentNullException if 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 is O(n), where n is 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));
    }
}

RELATED TAGS

c#
array
reverse
community creator
RELATED COURSES

View all Courses

Keep Exploring