Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse elements in an array

Tags:

arrays

c#

reverse

I setup an array and i would like to create a method that will return an array with the elements in reverse. e.g. if there are 10 slots then array1[9] = 6 so then array2[0] = 6.
I suppose i have to return an array - how would i do that?
And i dont know how to reverse and add to another array.
Thank you!

        int[] arr = {43, 22, 1, 44, 90, 38, 55, 32, 31, 9};
        Console.WriteLine("Before");
        PrintArray(arr);
        Console.WriteLine("After");
        Reverse(arr);

         Console.ReadKey(true);

    }

    static int[] Reverse(int[] array)
    {
        for (int i = array.Length; i < 1; i--)
        {
            int x = 0;

            array[i] = array[x++];
            Console.WriteLine(array[i]);
        }

       }


         static void PrintArray(int[] array)
    {
        for (int j = 0; j < array.Length; j++)
        {
            Console.Write(array[j] + " ");

        }
        Console.WriteLine("");
like image 985
baztown Avatar asked Dec 02 '22 18:12

baztown


2 Answers

You can use Array.Reverse

Example from above line

public static void Main()  {

  // Creates and initializes a new Array.
  Array myArray=Array.CreateInstance( typeof(String), 9 );
  myArray.SetValue( "The", 0 );
  myArray.SetValue( "quick", 1 );
  myArray.SetValue( "brown", 2 );
  myArray.SetValue( "fox", 3 );
  myArray.SetValue( "jumps", 4 );
  myArray.SetValue( "over", 5 );
  myArray.SetValue( "the", 6 );
  myArray.SetValue( "lazy", 7 );
  myArray.SetValue( "dog", 8 );

  // Displays the values of the Array.
  Console.WriteLine( "The Array initially contains the following values:" );
  PrintIndexAndValues( myArray );

  // Reverses the sort of the values of the Array.
  Array.Reverse( myArray );

  // Displays the values of the Array.
  Console.WriteLine( "After reversing:" );
  PrintIndexAndValues( myArray );
}


public static void PrintIndexAndValues( Array myArray )  {
  for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
     Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
}
like image 192
Ehsan Avatar answered Dec 04 '22 09:12

Ehsan


You should be able to use the extension method Reverse

int[] arr = { 43, 22, 1, 44, 90, 38, 55, 32, 31, 9 };
Console.WriteLine("Before");
PrintArray(arr);
Console.WriteLine("After");
PrintArray(arr.Reverse().ToArray());

Or if you don't mind modifing the original sequence you can use Array.Reverse

int[] arr = { 43, 22, 1, 44, 90, 38, 55, 32, 31, 9 };
Console.WriteLine("Before");
PrintArray(arr);
Array.Reverse(arr);
Console.WriteLine("After");
PrintArray(arr);
like image 24
sa_ddam213 Avatar answered Dec 04 '22 07:12

sa_ddam213