My assignment is to create an array with random numbers and then reverse the order in C#.
I managed to generate the random array, but how do i reverse it?
For example the output should look like this
15334 43351
int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i )
{
Random random = new Random();
int num = random.Next(TalArray.Length);
Console.WriteLine(num);
}
Thanks in advance! :)
CodePudding user response:
Here is a solution with Array.Reverse:
var arr = new int[5];
for (int i = 0; i < arr.Length; i )
{
arr[i] = new Random().Next(0, arr.Length);
}
var revArr = arr.Reverse();
Console.WriteLine(String.Join("", arr ) string.Join("", revArr));
CodePudding user response:
Have you tried Documentation
public static void Main()
{
int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i )
{
Random random = new Random();
int num = random.Next(TalArray.Length);
arr[i] = num;
Console.WriteLine(num);
}
Array.Reverse(arr);
for (int i = 0; i < arr.Length; i )
{
Console.WriteLine(arr[i]);
}
}
Working example dotnet fiddle