SnowwyWolf SnowwyWolf - 1 month ago 5
C# Question

How to reverse an array using three separate methods in C#

I'm currently going through an ebook in order to learn C# and I am currently at a place where I am stuck. I feel that once I have pushed through and understand this next bit, it will really accelerate my understanding and learning as I move on to classes next.

The current challenge I face I must do the following :


  • Make a program that uses methods to reverse an array.

  • Create three methods: one to create the array, one to print the array and one to reverse the array.

  • Ideally it would allow the user to input the desired length of the array.

  • Not allowed to use the reverse array method.



This is the code I have gotten so far but I'm extremely stuck on how to create the reverse method and I feel like what I currently have isn't what is required either. I just need that extra push here for it to click in place and for me to get the understanding I need. Feel free to just positions hints / tips / advice as oppose to the solution if you so wish.

Thank you all.


using System;

namespace Using_methods_to_reverse_an_array
{
class Program
{
static int[] CreateArray()
{
int[] array = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
return array;
}
static void PrintNumbers()
{
foreach (int numbers in CreateArray())
{
Console.WriteLine(numbers);
}
}
static void Main(string[] args)
{
int[] numbers = CreateArray();
PrintNumbers();
Console.ReadLine();
}
}
}

Answer

Maybe I misunderstood, but I think this should do it:

    class Program
        {
            static int[] CreateArray()
            {
                int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
                return array;
            }
//I changed this to receive an input array
            static void PrintNumbers( int[] inputArray)
            {
                foreach (int numbers in inputArray)
                {
                    Console.WriteLine(numbers);
                }
            }
//this function should reverse any array passed to it
            static void ReverseArray(int[] inputArray)
            {
                int len = inputArray.Length;
                int[] newArray = new int[len];
                foreach (int i in inputArray)
                {
                    newArray[i] = inputArray[len - 1];
                    len--;
                }
            }
            static void Main(string[] args)
            {
                int[] numbers = CreateArray();
                PrintNumbers(numbers);
                ReverseArray(numbers);
                //Console.ReadLine();
            }
        }
Comments