AshfaqFardin

Reverse array using pointer arithmetic

Jul 31st, 2021
1,820
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void printArray(int *arr, int size){
  6.     int *begin = arr;
  7.     int *end = arr + size - 1;
  8.    
  9.     while(begin <= end){
  10.         cout << *begin << " ";
  11.         begin++;
  12.     }
  13. }
  14. void reverseArray(int *arr, int size){
  15.     int *begin = arr;
  16.     int *end = arr + size - 1;
  17.    
  18.     while(begin <= end){
  19.         int temp = *begin;
  20.         *begin = *end;
  21.         *end = temp;
  22.        
  23.         begin++;
  24.         end--;
  25.     }
  26. }
  27.  
  28. int main()
  29. {
  30.     int size = 5;
  31.     int arr[] = {1, 2, 3, 4, 5};
  32.    
  33.     cout << "Original Form: ";
  34.     printArray(arr, size);
  35.    
  36.     cout << endl;
  37.     cout << "Reversed Form: ";
  38.     reverseArray(arr, size);
  39.     printArray(arr, size);
  40.    
  41.     return 0;
  42. }
  43.  
RAW Paste Data