Reverse an array in C#

 

Reverse an array in C#

In this article, we will see how to reverse an array in C#

1. Reverse an array using the in-build method | using the Reverse() method


1public static void ReverseArray()
2
3 {
4
5 int[] array = { 1, 2, 3, 4, 5 };
6
7 foreach (int a in array)
8
9 {
10
11 Console.WriteLine(a);
12
13 }
14
15 Array.Reverse(array);
16
17 Console.WriteLine("Reversed Array : ");
18
19 foreach (int value in array)
20
21 {
22
23 Console.WriteLine(value);
24
25 }
26
27 Console.ReadLine();
28
29
30
31 }
C#
output


2. Reverse an array without using the Reverse() method


1 public static void ReverseArray()

2
3 {
4
5 int[] arr = new int[] { 1, 2, 3, 4, 5 };
6
7 int length = arr.Length - 1;
8
9 string strReverse = null;
10
11 while (length >= 0)
12
13 {
14
15
16
17 strReverse = strReverse + arr[length] + Environment.NewLine;
18
19 length--;
20
21 }
22
23 Console.WriteLine();
24
25 Console.WriteLine("Reverse Array is " + " " + strReverse);
26
27 Console.ReadLine();
28
29
30
31 }
C#




Share this

Related Posts

Previous
Next Post »