Introduction
In this snippet we will write a program which reverses an array using for loop in c#.
Example: If input array is {1,2,3,4,5,6,7} , we should print {7,6,5,4,3,2,1}
From below program using C# for loop, we are basically shifting all array elements from left side to right side.
Program
using System;
namespace DotNetMirror
{
class ArrayReverseWithForLoop
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5, 6, 7 }; //user input
int arrLen = array.Length;
int j = 0;
int[] revArray = new int[arrLen]; //take same length of source array to reverse
for (int i = arrLen - 1; i >= 0; i--)
{
revArray[j] = array[i];
j++; //increment target array index
}
Console.WriteLine("Result: {0}", string.Join(",", revArray));
Console.ReadKey();
}
}
}
Output
Result: 7,6,5,4,3,2,1
Source Code
https://github.com/dotnetmirror/Rev_Array_Using_For_Loop