Advertisement
YouKnowWho07

Rotate n element

Dec 25th, 2023
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.79 KB | None | 0 0
  1. ///C program to rotate an array by n positions to the left, with a separate function for single left rotation:
  2. #include <stdio.h>
  3.  
  4. void rotate_left(int arr[], int n) {
  5.     int temp = arr[0];
  6.     for (int i = 0; i < n - 1; i++) {
  7.         arr[i] = arr[i + 1];
  8.     }
  9.     arr[n - 1] = temp;
  10. }
  11.  
  12. int main() {
  13.     int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  14.     int n = sizeof(arr) / sizeof(arr[0]);
  15.     int d = 3;  // Number of positions to rotate
  16.  
  17.     printf("Original array: ");
  18.     for (int i = 0; i < n; i++) {
  19.         printf("%d ", arr[i]);
  20.     }
  21.  
  22.     // Rotate the array d times
  23.     for (int i = 0; i < d; i++) {
  24.         rotate_left(arr, n);
  25.     }
  26.  
  27.     printf("\nRotated array: ");
  28.     for (int i = 0; i < n; i++) {
  29.         printf("%d ", arr[i]);
  30.     }
  31.  
  32.     return 0;
  33. }
  34.  
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement