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

Result

C++ language techstudy.org

     





Related Topics




Popular Posts