Answer to Question #155861 in C++ for zain ul abdeen

Question #155861

Write a program to copy the contents of one array into another in the reverse order.


1
Expert's answer
2021-01-18T01:11:47-0500

/*


Program workflow:

1) User enters length of array

2) User enters elements of array, delimited by space

3) Program creates reversed array, using function reverse()

4) Program outputs reversed array


*/


#include <iostream>

#include <string>


template<class T>

T * reverse(T * array, int length) {

 T * result = new T[length];

 for (int i = 0; i < length; ++i) {

   // fill reversed array with original array elements, starting from the end of original array

   result[i] = array[length - 1 - i];

 }

 return result;

}


int main() {

 std::cout << "Enter array length: ";

 int length;

 std::cin >> length;

 std::string * array = new std::string[length];

 std::cout << "Enter array elements, delimited by space: ";

 for (int i = 0; i < length; ++i) {

   std::string str;

   std::cin >> str;

   array[i] = str;

 }

 // reversed array

 std::string * reversed = reverse(array, length);

 std::cout << "Reversed array: ";

 for (int i = 0; i < length; ++i) {

   std::cout << reversed[i];

   if (i < length - 1) {

     std::cout << " ";

   }

 }

 std::cout << "\n";

 delete[] array;

 delete[] reversed;

 return 0;

}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS