Write C++ program to left rotate an array


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. #define size 5 // defining Size of the array
  3. using namespace std;
  4.  
  5. void printArray(int arr[]);
  6. void rotateByOne(int arr[]);
  7.  
  8.  
  9. int main()
  10. {
  11. int i, num;
  12. int arr[size];
  13.  
  14. cout<<"Enter 5 elements array: ";
  15. for(i=0; i<size; i++)
  16. {
  17. cin>>arr[i];
  18. }
  19. cout<<"Enter number of times to left rotate: ";
  20. cin>>num;
  21.  
  22. // Actual rotation
  23. num = num % size;
  24.  
  25. // Printing array before rotation
  26. cout<<"Array before rotationn:\n "<<endl;
  27. printArray(arr);
  28.  
  29. // Rotating array n times
  30. for(i=1; i<=num; i++)
  31. {
  32. rotateByOne(arr);
  33. }
  34.  
  35. // Printing array after rotation
  36. cout<<"\nArray after rotation: "<<endl;
  37. printArray(arr);
  38.  
  39. return 0;
  40. }
  41.  
  42. void rotateByOne(int arr[])
  43. {
  44. int i, first;
  45.  
  46. // Storing first element of array
  47. first = arr[0];
  48.  
  49. for(i=0; i<size-1; i++)
  50. {
  51. // Moving each array element to its left
  52. arr[i] = arr[i + 1];
  53. }
  54.  
  55. // Copying the first element of array to last
  56. arr[size-1] = first;
  57. }
  58.  
  59.  
  60. //Printing the given array
  61.  
  62. void printArray(int arr[])
  63. {
  64. int i;
  65.  
  66. for(i=0; i<size; i++)
  67. {
  68. cout<<arr[i]<<"\t";
  69. }
  70. }
  71.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts