w3resource

C#: Rotate an array of integers in left direction


Rotate Array Left

Write a C# program to rotate an array (length 3) of integers in the left direction.

Pictorial Presentation:

>C# Sharp Exercises: Rotate an array of integers in left direction

Sample Solution:

C# Sharp Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Exercise50
{  
    public static void Main() 
    {
        // Define an array of integers 'nums' with pre-defined values
        int[] nums = {1, 2, 8};

        // Display the elements of 'nums' array using string.Join to concatenate them
        Console.WriteLine("\nArray1: [{0}]", string.Join(", ", nums));

        var temp = nums[0]; // Store the first element of 'nums' in a temporary variable 'temp'

        // Iterate through the elements of the 'nums' array (except the last element) using a for loop
        for (var i = 0; i < nums.Length - 1; i++)
        {
            nums[i] = nums[i + 1]; // Shift each element one place to the left
        }

        nums[nums.Length - 1] = temp; // Assign the value of 'temp' to the last element of 'nums'

        // Display the elements of the modified 'nums' array after rotation
        Console.WriteLine("\nAfter rotating array becomes: [{0}]", string.Join(", ", nums));
    } 
}

Sample Output:

Array1: [1, 2, 8]                                                      
                                                                       
After rotating array becomes: [2, 8, 1]

Flowchart:

Flowchart: C# Sharp Exercises - Rotate an array of integers in left direction

For more Practice: Solve these Related Problems:

  • Write a C# program to rotate an array of size n to the right.
  • Write a C# program to rotate an array to the left by k positions.
  • Write a C# program to rotate elements circularly in a jagged array.
  • Write a C# program to rotate a 2D matrix left or right based on user input.

Go to:


PREV : First or Last Element Equal in Two Arrays.
NEXT : Max of First and Last in Array.

C# Sharp Code Editor:



What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.