OneBite.Dev - Coding blog in a bite size

reverse arrays items in C

Code snippet on how to reverse arrays items in C

  void reverse(int arr[], int start, int end) 
  { 
    while (start < end) 
    { 
        int temp = arr[start];  
        arr[start] = arr[end]; 
        arr[end] = temp; 
        start++; 
        end--; 
    }  
  } 

This code reverses an array by swapping the elements starting from the first and the last element, and then moving towards the center of the array. The function takes three parameters: an array, a starting point, and an ending point. The starting point is set to the first element of the array, and the ending point is set to the last element of the array. We then use a while loop to keep going until the starting point is no longer less than the ending point. Every time the loop runs, we store the starting point element in a temporary variable, then swap it with the value of the ending point element. Lastly, the starting and ending points are incremented and decremented respectively, so that the next iteration of the loop operates on the elements adjacent to the ones used for the current iteration.

c