In: Computer Science
C++
9.10: Reverse Array Write a function that accepts an int array and the array’s size as arguments. The function should create a copy of the array, except that the element values should be reversed in the copy. The function should return a pointer to the new array. Demonstrate the function by using it in a main program that reads an integer N (that is not more than 50) from standard input and then reads N integers from a file named data into an array. The program then passes the array to the your reverse array function, and prints the values of the new reversed array on standard output, one value per line. You may assume that the file data has at least N values. Prompts And Output Labels. There are no prompts for the integer and no labels for the reversed array that is printed out. Input Validation. If the integer read in from standard input exceeds 50 or is less than 0 the program terminates silently.
Code
#include <iostream>
#include <string>
#include<fstream>
using namespace std;
int* reverseArray(int arr[], int N)
{
int j = N - 1;
int *newArray = (int*)malloc(N * sizeof(int));
for (int i = 0; i < N; i++)
newArray[i] = arr[j--]; //
assigning value to new array in reverse order from original
array.
return newArray;
}
int main()
{
int N = 0, *arr=NULL, *revArr=NULL;
cout << "Enter the number of elements" <<
endl;
cin >> N;
// Input Validation
if (N <= 0 || N > 50)
return 0;
// Dynamically create an array with N
elements
arr = (int*)malloc(N * sizeof(int));
// Read the array value from file named
"data.txt"
ifstream file ("data.txt");
if (file.is_open())
{
for (int i = 0; i < N;
i++)
{
string
line;
getline(file,
line); // Reading each number as string
arr[i] =
atoi(line.c_str()); // converting into integer and storing in
array
}
}
else
{
cout << "could not open the
file\n";
return 0;
}
revArr = reverseArray(arr, N);
cout << endl;
for (int i = 0; i < N; i++)
cout << revArr[i] <<
endl;
return 0;
}
Test Input
data.txt file
Test Output