Advertisement
alkelane7

question 4

Mar 16th, 2019
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. #include <iostream.h>
  2. #define size 5 // defining Size of the array
  3.  
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement