Reverse an Array in CThe task is to reverse the elements of the given array. We can use many approaches to do this, and it is a basic problem. It is one of the most frequently asked questions in interviews. This tutorial lists all the possible approaches to reversing an array in C. For example, Suppose given an array: We need to reverse the array and print the following: We can use list slicing in Python and specify the step as -1 -> list [::-1] to get the reversed list. In C, there is no slicing mechanism. Hence, we need to dive into lower-level solving. Possible Approaches:
1. Declaring another arrayWe can declare another array, iterate the original array from backward and send them into the new array from the beginning. Code: Output: Enter the size of the array: 5 Enter the elements: 1 2 3 4 5 The Reversed array: 5 4 3 2 1 Here is an example: If the array is: We create another array rev with the same size = 6: First iteration: i = n - 1 = 5, i >= 0, j = 0 rev[0] = arr[5] In the same way: Second iteration: rev[1] = arr[4] Third iteration: rev[2] = arr[3] Fourth iteration: rev[3] = arr[2] Fifth iteration: rev[4] = arr[1] Sixth iteration: rev[5] = arr[0] Hence, the resultant reversed array: 2. Iteration and swappingIterating half of the array: We iterate the array till size/2, and for an element in index i, we swap it with the element at index (size - i - 1). Here is an example: If the array is: size = 6, size/2 = 3 First iteration: i = 0, i < 3 We swap arr[i] with arr[n - i - 1] arr[0] <-> arr[5] Second iteration: i = 1, i < 3 We swap arr[i] with arr[n - i - 1] arr[1] <-> arr[4] Third iteration: i = 2, i < 3 We swap arr[i] with arr[n - i - 1] arr[2] <-> arr[3] Termination when i = 3 as i == n/2 The resultant reversed array: Code: Output: Enter the size of the array: 6 Enter the elements: 1 2 3 4 5 6 The reversed array: 6 5 4 3 2 1 Iterating from two ends of the array: We can keep iterating and swapping elements from both sides of the array till the middle element. Code: Output: Enter the size of the array: 6 Enter the elements: 1 2 3 4 5 6 The Reversed array: 6 5 4 3 2 1 Here is an example: If the array is: size = 6 l = 0, h = size - 1 = 5 First iteration: l = 0, h = 5 We swap arr[l] with arr[h] arr[0] <-> arr[5] Second iteration: l = 1, h = 4 We swap arr[l] with arr[h] arr[1] <-> arr[4] Third iteration: l = 2, h = 3 We swap arr[l] with arr[h] arr[2] <-> arr[3] Termination when l = h = 3 as l !< h The resultant reversed array: Recursive Way:Output: Enter the size of the array: 6 Enter the elements: 1 2 3 4 5 6 The reversed array: 6 5 4 3 2 1 3. Using pointersA pointer is like a special variable that can hold the addresses of other variables and pointers. We can swap the array elements using pointers rather than traditional array indexes. Important points about pointers:
Code: Output: Enter the size of the array: 6 Enter the elements into the array: 1 2 3 4 5 6 The reversed array: 6 5 4 3 2 1 Understanding:
Next Topic3 way merge sort in c |