ARRAY REVERSAL: Why are PRINTING and REVERSING not the same?
UNDERSTAND THE CONCEPT: REVERSING vs PRINTING
When asked about reversing a given array, some/many of us often think why not print the whole array just in reverse order since it also produces the same output as when we reverse an array with logic.
BUT, THAT'S NOT THE CASE. LET'S DIVE IN.
Reversing:
Reversing an array refers to modifying the order of the elements within the array itself. Imagine swapping the elements from the beginning to the end so that the first element becomes the last, the second becomes the second-to-last, and so on.
After reversing, the original order of the elements is flipped.
Printing:
Printing simply displays the values of the array elements, either in their original or modified order.
Printing in reverse order doesn't change the underlying array. It just iterates through the elements and displays them starting from the end, creating the illusion of a reversed array.
Take a look at this snippet:
int arr[] = {1, 2, 3, 4, 5};
// Reversing (modifies the array)
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
// Printing in reverse order (doesn't modify the array)
for (int i = arr.length - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
In this example:
The first loop reverses the order of elements in the arr array.
The second loop iterates through the array from the end (i = arr.length - 1) to the beginning (i >= 0) and prints the elements, giving the impression of a reversed array, but the original arr remains reversed.
Understanding the difference between reversing and printing is crucial for various programming tasks:
If you need to process the elements in the reversed order (e.g., finding the largest element from the end), you need to perform a true reversal.
If you simply want to display the elements in the opposite order for visual purposes, printing in reverse order might be sufficient.