# Array Left Rotation in C#

Problem source: Left Rotation – Hackerrank

Input:

n = number of items in array

r = number of rotations

arr = integer array

Output:

Array items after “r” left rotation.

Example:

n = 5

r = 3

Arr = [1, 2, 3, 4, 5]

Output:

4 5 1 2 3

Explanation:

Original Array: 1 2 3 4 5

1st rotation: 2 3 4 5 1

2nd rotation: 3 4 5 1 2

3rd rotation: 4 5 1 2 3

Algorithm:

1. If r % n = 0 that means there is no need of rotation because array items will be in same position after rotation.
2. If r % n = i then we’ll split our original array into two parts.
1. First part will have items from i to n.
2. Second part will have items form 0 to i -1;
3. Print this new array.

C# code:

```static void Main(String[] args)
{
var n = Convert.ToInt32(strInput[0]);
var r = Convert.ToInt32(strInput[1]);
var arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
var finalRotationCount = r % n;
if (finalRotationCount > 0)
{
var temp = new int[n];
for (int i = 0; i < n - finalRotationCount; i++)
{
temp[i] = arr[finalRotationCount + i];
}

for (int i = 0; i < finalRotationCount; i++)
{
temp[n - finalRotationCount + i] = arr[i];
}

arr = temp;
}
Console.WriteLine(string.Join(" ", arr));
}
```

## 2 thoughts on “Array Left Rotation in C#”

1. sanjay says:

—HACKER RANK Problem:
static void Main(string[] args)
{
TextWriter textWriter = new StreamWriter(@”outputpath here”, true);

int n = Convert.ToInt32(nd[0]);

int d = Convert.ToInt32(nd[1]);

int[] a = Array.ConvertAll(Console.ReadLine().Split(‘ ‘), aTemp => Convert.ToInt32(aTemp));
int[] result = rotLeft(a, d);

textWriter.WriteLine(string.Join(” “, result));

textWriter.Flush();
textWriter.Close();
}

static int[] rotLeft(int[] a, int d)
{
int m = 1;
while (m <= d)
{
var temp = a[0];
for (var i = 0; i < a.Length – 1; i++)
{
a[i] = a[i + 1];
}
a[a.Length – 1] = temp;
Console.WriteLine("\nAfter rotating array becomes: [{0}]", string.Join(", ", a));
m = m + 1;
}
return a;
}

Like