Array reverse
In this chapter you will learn:
- Reverse an array using Array.Reverse
- Reverse an array in a range
- Use the Reverse() method to reverse the elements in string Array
Reverse an array
using System; /* j a v a2s.com*/
class MainClass {
public static void Main() {
int[] nums = { 1, 2, 3, 4, 5 };
Console.Write("Original order: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
Array.Reverse(nums);
Console.Write("Reversed order: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
}
}
The code above generates the following result.
Reverse an array in a range
The following code passes value to Array.Reverse() and only reverse part of an array.
using System; /*from j a va 2s . c o m*/
class MainClass {
public static void Main() {
int[] nums = { 1, 2, 3, 4, 5 };
Console.Write("Original order: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
// Reverse a range.
Array.Reverse(nums, 1, 3);
// Display reversed order.
Console.Write("Range reversed: ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
}
}
The code above generates the following result.
Reverse a string array
using System;// java 2s . c o m
class MainClass
{
public static void Main()
{
string[] stringArray = {"t", "i", "a", "java2s.com", "abc123", "abc345"};
Array.Sort(stringArray);
Array.Reverse(stringArray);
Console.WriteLine("Reversed stringArray:");
for (int i = 0; i < stringArray.Length; i++)
{
Console.WriteLine("stringArray[" + i + "] = " + stringArray[i]);
}
}
}
Next chapter...
What you will learn in the next chapter:
- Convert all elements from one type to another type
- Convert all string elements from lower case to upper case
- Convert an array of floats to an array of integers
Home » C# Tutorial » Array