In this snippet, we will see How to reverse an array in C#
In this snippet, we will learn How to reverse an array in C#. In C#, with the use of Array.Reverse() method, we can easily reverse the order of the elements in a one-dimensional array or in the proportion of the array.
Program to reverse an array in C#:
static void Main(string[] args)
{
//Initial Array
int[] arr = { 1, 2, 5, 4, 6, 8, 7, 10 };
Console.WriteLine("Intial Array:");
//Print all values of array on console
foreach (int val in arr) {
Console.WriteLine(val);
}
//Reverse the order of the elements in a one dimensional array
Array.Reverse(arr);
Console.WriteLine("Reverse Array:");
//Print all values of array on console
foreach (int val in arr)
{
Console.WriteLine(val);
}
//Console.ReadLine() to hold the screen after the execution of the program
Console.ReadLine();
}
Preview:
I hope this program will help you in your interview/exam.