
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
How to rotate an array k time using C#?
Given an array and number k, the problem states that we have to rotate the array k times.
If the given number is 3 then the array must be rotated 3 times.
Create a function reverse which takes the array, start and end as a parameter.
In the 1st step call reverse method from 0 to array length.
In the 2nd step call the reverse method from 0 to k-1.
In the 3rd step call the reverse method from k+1 to array length.
Example
using System; namespace ConsoleApplication{ public class Arrays{ public void ReverseArrayKTimes(int[] arr, int k){ Reverse(arr, 0, arr.Length - 1); Reverse(arr, 0, k - 1); Reverse(arr, k, arr.Length - 1); } private void Reverse(int[] arr, int start, int end){ while (start < end){ int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } } class Program{ static void Main(string[] args){ Arrays a = new Arrays(); int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; a.ReverseArrayKTimes(arr, 3); for (int i = 0; i < arr.Length; i++){ Console.WriteLine(arr[i]); } Console.ReadLine(); } } }
Output
3 2 1 9 8 7 6 5 4
- Related Articles
- How to rotate an image with OpenCV using Java?
- How to rotate an image in OpenCV using C++?
- Golang Program to Rotate Elements of an Array
- How to rotate a matrix of size n*n to 90-degree k times using C#?
- Python program to cyclically rotate an array by one
- Java program to cyclically rotate an array by one.
- Python program to left rotate the elements of an array
- Python program to right rotate the elements of an array
- How to rotate an image in imageview by an angle on Android using Kotlin?
- Java program to program to cyclically rotate an array by one
- PyTorch – How to rotate an image by an angle?
- How to rotate an image in imageview by an angle on iOS App using Swift?
- Rotate List Left by K in C++
- How to rotate an image in Node Jimp?
- How to rotate an image in OpenCV Python?

Advertisements