Write a function that accepts an array of integers and the array\'s size as argu
ID: 3570923 • Letter: W
Question
Write a function that accepts an array of integers and the array's size as arguments. The function should create a copy of the array, except that the values should be reversed in the copy. The function should return a pointer to the new array. Write a main function which uses this function and asks users
for values in an array, outputting the reversed array afterwards.
Sample output:
How many numbers do you have in your array? 3
Enter value #1: 51
Enter value #2: 16
Enter value #3: 97
97 16 51
Need to use C++
Explanation / Answer
C++ Program that accepts an array of integers and the array's size as arguments :
#include<iostream>
#include<fstream>
using namespace std;
// Prototype
int *reverseArray(int[], int);
void showArray(int[], int);
int main()
{
const int SIZE = 50;
int values[SIZE];
int n;
cin >> n;
if (n<0 || n>=SIZE)
return 0;
ifstream inFile;
inFile.open("data");
for (int k=0; k> values[k];
inFile.close();
// Make a reverse copy of the array.
int *arrCopy = reverseArray(values, n);
// Display the contents of the new array.
showArray(arrCopy, n);
return 0;
}
// ********************************************************
int *reverseArray(int arr[], int size)
{
int sourceIndex; // Index into the source array
int targetIndex; // Index into the target array
if (size <= 0)
return NULL;
int *copy = new int[size];
// Copy arr's elements, in reverse order, to
// the new array.
for (sourceIndex = size - 1, targetIndex = 0; // Initialization expression
sourceIndex >= 0; // Test expression
sourceIndex--, targetIndex++) // Update expression
{
copy[targetIndex] = arr[sourceIndex];
}
return copy;
}
void showArray(int arr[], int size)
{
for (int index = 0; index < size; index++)
cout << arr[index] << endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.