As newbie to C# I try to reverse an array with a method. But it returns not the reversed array. I tried for hours but still don't get it what I am doing wrong. The whole thing is a lesson from "The C# Players guide - 2nd edition" book I have bought. Unfortunately the solutions of the lessons are not included in the book. The Main method ist predefined and should be used like you can see.
If I do the output within the for loop it is 54321 and this would be fine. But the correct output should come from the PrintNumbers method. And there is the problem because the output 12345 is not reversed
Here is the code, please tell me if you see something bad.
class Program
{
static void Main(string[] args)
{
int[] numbers = GenerateNumbers();
Reverse(numbers);
PrintNumbers(numbers);
Console.ReadKey();
}
//Generate the array and return the numbers
static int[] GenerateNumbers()
{
int[] temp;
temp = new int[] { 1, 2, 3, 4, 5 };
return temp;
}
//Reverse the numbers in the array
static int[] Reverse(int[] numbersToSwap)
{
//Write array length in value to decrement later
int numbersLenghtMax = numbersToSwap.Length;
//Minus 1 because an array starts with 0
numbersLenghtMax--;
//Create a temp value to store last value of array
int[] temp = new int[numbersToSwap.Length];
for (int index = 0; index < numbersToSwap.Length; index++)
{
//Store values reversed in the temp value
temp[index] = numbersToSwap[numbersLenghtMax];
numbersLenghtMax--;
//This output is correct
Console.Write(temp[index]);
}
Console.WriteLine();
//The returned array is not reversed
return temp;
}
//Print out the numbers
static void PrintNumbers(int[] numbers)
{
foreach (int number in numbers)
Console.Write(number);
}
}
Reversemethod. The argumentnumbers/numbersToSwapis not modified.System.LinqorArray.Reverse()to reverse your arrayArray.Reverse()but the lesson is to do it without. Because it is about learning how functions work.