Skip to content

Reverse A Given Integer Array Using Loop

We are going to find how to reverse an integer array using loop. We will use while and for loop in this post.

The approach is simple and it is to traverse the array to its length.

In order to execute the code I’ve created a simple console application to print out the result.

Please find complete code below:

  1. Using While loop
using System;

namespace PracticeConsole
{
   class Program
   {
      static void Main(string[] args)
      {
         int[] integerArray = new int[] { 1, 2, 3, 4, 5 };
         int length = integerArray.Length - 1;
         string strReverse = null;
         while (length >= 0)
         {
            strReverse = strReverse + integerArray[length] + " ";
            length--;
         }
         Console.WriteLine("Reversed array: " + strReverse);
         Console.ReadLine();
      }
   }
}

Result:

 

2. Using For loop

using System;

namespace PracticeConsole
{
   class Program
   {
      static void Main(string[] args)
      {
         for (int i = 0; i < integerArray.Length / 2; i++)
         {
            int tmp = integerArray[i];
            integerArray[i] = integerArray[integerArray.Length - i - 1];
            integerArray[integerArray.Length - i - 1] = tmp;
         }
         Console.WriteLine("Reversed array: " + string.Join(", ", integerArray));
         Console.ReadLine();
      }
   }
}

Result: