CPP   116

array reverse

Guest on 18th June 2022 08:12:02 AM

  1. // getline with strings
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. int main ()
  7. {
  8.     int array[5]={2,5,8,10,15};
  9.     int temp;
  10.  
  11.     // Get the size of the array and go one less to get the
  12.     // last element.
  13.     int last_element=sizeof(array)/sizeof(int)-1;
  14.     int size=sizeof(array)/sizeof(int);
  15.  
  16.     // Reverse the values into a new array.
  17.     for (int i=0;i<size/2;i++)
  18.     {
  19.         // Make a copy.
  20.         temp=array[i];
  21.  
  22.         // Swap.
  23.         array[i]=array[last_element-i];
  24.         array[last_element-i]=temp;
  25.     }
  26.     // Print the array in reverse order.
  27.     for (int i=0;i<size;i++)
  28.         cout<< array[i] << endl;
  29.  
  30.  
  31.     return 0;
  32. }

Raw Paste


Login or Register to edit or fork this paste. It's free.