EN
C# / .NET - reverse array
0 points
In this article, we would like to show you how to reverse array in C#.
Quick solution:
xxxxxxxxxx
1
int[] myArray = new int[] { 1, 2, 3 };
2
3
Array.Reverse(myArray);
or:
xxxxxxxxxx
1
int[] myArray = new int[] { 1, 2, 3 };
2
3
for (int i = 0; i < myArray.Length / 2; i++)
4
{
5
int tmp = myArray[i];
6
myArray[i] = myArray[myArray.Length - i - 1];
7
myArray[myArray.Length - i - 1] = tmp;
8
}
In this example, we use Array.Reverse()
method to reverse array.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main()
6
{
7
int[] myArray = new int[] { 1, 2, 3 };
8
9
// reverse array
10
Array.Reverse(myArray);
11
12
// display result
13
foreach (int item in myArray)
14
Console.WriteLine(item);
15
}
16
}
Output:
xxxxxxxxxx
1
3
2
2
3
1
In this example, we use simple for loop to reverse array.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main()
6
{
7
int[] myArray = new int[] { 1, 2, 3 };
8
9
// reverse myArray
10
for (int i = 0; i < myArray.Length / 2; i++)
11
{
12
int tmp = myArray[i];
13
myArray[i] = myArray[myArray.Length - i - 1];
14
myArray[myArray.Length - i - 1] = tmp;
15
}
16
17
// display result
18
foreach (int item in myArray)
19
Console.WriteLine(item);
20
}
21
}
Output:
xxxxxxxxxx
1
3
2
2
3
1
Note:
We only iterate through half the length of the array, otherwise it will be reversed twice.