C++ Program to Copy the Contents of One Array Into Another in the Reverse Order
Last Updated :
17 Jan, 2023
Given an array, the task is to copy these array elements into another array in reverse array.
Examples:
Input: array: 1 2 3 4 5
Output: 5 4 3 2 1
Input: array: 10 20 30 40 50
Output: 50 40 30 20 10
Let len be the length of original array. We copy every element original_arr[i] to copy_arr[n-i-1] to get reverse in copy_arr[].
C++
#include <stdio.h>
void printArray( int arr[], int len)
{
int i;
for (i = 0; i < len; i++) {
printf ( "%d " , arr[i]);
}
}
int main()
{
int original_arr[] = {1, 2, 3, 4, 5};
int len = sizeof (original_arr)/ sizeof (original_arr[0]);
int copied_arr[len], i, j;
for (i = 0; i < len; i++) {
copied_arr[i] = original_arr[len - i - 1];
}
printf ("
Original array: ");
printArray(original_arr, len);
printf ("
Resultant array: ");
printArray(copied_arr, len);
return 0;
}
|
Output:Â
Original array: 1 2 3 4 5
Resultant array: 5 4 3 2 1
Â
Time Complexity: O(len)
Auxiliary Space: O(len)
Share your thoughts in the comments
Please Login to comment...