Back to: C#.NET Programs and Algorithms
How to Perform Right Circular Rotation of an Array in C#
In this article, I am going to discuss How to Perform Right Circular Rotation of an Array in C# with an example. Please read our previous article where we discussed How to Perform Left Circular Rotation of an Array in C# with an example.
Program Description:
Here, the user will input a one-dimensional integer array. Then we need to shift each element of the array to its right by one position in a circular fashion. The logic that we need to implement should iterate the loop from 0 t0 Length – 1 and then swap each element with the first element. Please have a look at the following diagram for a better understanding of our requirement.
Right Circular Rotation of an Array in C#:
In the following example, first we take the input integer array from the user. Then we perform right circular rotation using for loop.
using System; namespace LogicalPrograms { class Program { static void Main(string[] args) { int[] oneDimensionalArray = new int[6]; Console.WriteLine("Enter the 1D Array Elements : "); for (int i = 0; i<oneDimensionalArray.Length; i++) { oneDimensionalArray[i] = int.Parse(Console.ReadLine()); } int temp; for (int j = 0; j < oneDimensionalArray.Length - 1; j++) { temp = oneDimensionalArray[0]; oneDimensionalArray[0] = oneDimensionalArray[j + 1]; oneDimensionalArray[j + 1] = temp; } Console.WriteLine("Array Elements After Right Circular Rotation: "); foreach (int num in oneDimensionalArray) { Console.Write(num + " "); } Console.ReadKey(); } } }
Output:
In the next article, I am going to discuss how to find the angle between the hour and minute hands of a clock at any given time in C# with examples. I hope now you understood How to Perform Right Circular Rotation of an Array in C#.
int[] arr = Enumerable.Range(1, 6).ToArray();
//1,2,3,4,5,6
//6,1,2,3,4,5
int temp = arr[arr.Length – 1];
for(int i = arr.Length – 1; i>0; i–)
{
arr[i] = arr[i – 1];
}
arr[0] = temp;
foreach (int num in arr)
{
Console.WriteLine(num);
}