Copying an array in the reverse order in C++
Hi, this is Mazen. Today I'm going to solve with you a new programming example. Today's example is like an enhanced model of the previous one. We declare two arrays, assign some values to one of them, and then copy the elements to the unassigned array. Before copying the elements, we reverse them. So they're being copied in the reversed order, the element in the last index goes into the first index; the last index's value of the first array goes into the first index in the second. In this example we assume that the array being copied has the size of 10. It can have any size but make sure that both of the two arrays - the source and destination - have the same size.
The question says:
Take 10 integer inputs from the user and store them in an array. Then copy all the elements into another array but in the reverse order.
Step 1: Declare an integer array with the size of 10 and name it "array", for instance.
int array[10];
Step 2: Use a for loop to pass through the array indexes and prompt the user to enter a value for each of them.
std::cout << "Enter ten integers:\n"; for (int i = 0; i < 10; i++) std::cin >> array[i];
Step 3: Declare another array into which elements are going to be copied. Its size and data type must be the same as the source array.
int array_copy[10];
for (int i = 0; i < 10; i++) array_copy[i] = array[9 - i];
Step 5: Finally, output the elements of the reversed array using a for loop just like the previous one.
std::cout << "The elements of the reversed array:\n";
for (int i = 0; i < 10; i++) std::cout << array_copy[i] << '\t';
Putting it all together:
#include <iostream>
int main()
{
int array[10];
std::cout << "Enter ten integers:\n";
for (int i = 0; i < 10; i++)
{
std::cout << "Integer #" << i + 1 << ": ";
std::cin >> array[i];
}
int array_copy[10];
for (int i = 0; i << 10; i++)
array_copy[i] = array[9 - i];
std::cout << "The elements of the reversed array:\n";
for (int i = 0; i < 10; i++)
std::cout << array_copy[i] << '\t';
std::cout << "\n\n";
system("pause");
return 0;
}
Outputs
That was our example for today, I hope you got benefit of it. See you in the coming programming example, InShaAllah.
Comments
Post a Comment