CodeBlanks Logo Icon CodeBlanks

Array.Reverse

C# course · Beginner · Lesson 60/116

Learn to reverse an array with Array.Reverse.

Array.Reverse

Array.Reverse reverses the order of elements in an array. The first element moves to the end, the last to the front. Like Array.Sort, this is done in place; it changes the array itself.

After int[] nums = { 1, 2, 3 }; Array.Reverse(nums);, the nums array becomes { 3, 2, 1 }. Reverse does not sort by itself; it only flips the existing order.

Descending sort

Array.Sort only sorts ascending. For a descending sort you need two steps: first sort ascending with Array.Sort, then reverse with Array.Reverse.

For example, on the array { 78, 92, 65 }, applying Sort first gives { 65, 78, 92 }; applying Reverse afterwards leaves { 92, 78, 65 }. The array is now sorted descending.

Exercise Sort, reverse and print the first element

On the given int[] scores = { 78, 92, 65, 88 }; array, first sort ascending with Array.Sort(scores), then reverse with Array.Reverse(scores). Then print the first element with Console.WriteLine.

Show example solution
First sort with Array.Sort(scores);, then reverse with Array.Reverse(scores);, finally print with Console.WriteLine(scores[0]);.
Example solution:
using System;

class Program
{
    static void Main()
    {
        int[] scores = { 78, 92, 65, 88 };
        // Sort, reverse and print the first element
        Array.Sort(scores);
        Array.Reverse(scores);
        Console.WriteLine(scores[0]);
    }
}

Test yourself

  1. Array.Reverse call

    int[] nums = { 1, 2, 3 };
    ____
    Console.WriteLine(nums[0]);
    Show answer
    int[] nums = { 1, 2, 3 };
    Array.Reverse(nums);
    Console.WriteLine(nums[0]);
  2. What does nums[0] print after Reverse?

    int[] nums = { 1, 2, 3 };
    Array.Reverse(nums);
    Console.WriteLine(nums[0]);
    • 1
    • 2
    • 3
    • 0
    Show answer

    3 — Correct. Reverse turns {1,2,3} into {3,2,1}; nums[0] is now 3.

  3. Match each expression to its meaning

    Array.Reverse(nums)
    Reverses order
    Array.Sort(nums)
    Sorts ascending
    Sort + Reverse
    Sorts descending
    nums[0]
    First element

All lessons in Beginner