Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

All code must be in C++ using G++ compiler Write a program that asks the user to

ID: 3809604 • Letter: A

Question

All code must be in C++ using G++ compiler

Write a program that asks the user to enter the size for an array (greater than 0) and fills the array with a set of random numbers between 1 and the number entered by the user. The creation of the array should happen inside the main() function and the initialization of the array should happen inside initializeArray() function that takes the array and its size as arguments. Print the array using a function called displayArray(). Next reverse the array using a function called reverseArray(), and print the reversed array. Example: Enter the size of your array: 5 Array contains: 153 54 Reversed array: 4 5 351

Explanation / Answer

#include <iostream>
using namespace std;

void initializeArray( int array[], int arraylength ){
for (int i = 0; i < arraylength; i++)
array[i] = rand() % arraylength + 1;
}

void reverseArray( int array[], int arraylength )
{
for (int i = 0; i < (arraylength / 2); i++) {
int temporary = array[i]; // temporary wasn't declared
array[i] = array[(arraylength - 1) - i];
array[(arraylength - 1) - i] = temporary;
}
}

void displayArray( int array[], int arraylength ){
for (int i = 0; i < arraylength ; i++)
cout<<array[i]<<" ";
cout<<endl;
}

int main()
{
int arraylength; // unused variable temporary?

cout << "Enter the array size: ";
cin >> arraylength;
  
int* array = new int[arraylength];

cout << "Enter the numbers in the array:" << endl;
initializeArray(array,arraylength);
cout<<"Array contains :";displayArray(array,arraylength);
reverseArray(array, arraylength );
cout<<"Reversed array :";displayArray(array,arraylength);

// free the memory, to prevent memory leaks
delete[] array;
}

Output :

Online URL : http://ideone.com/GFaTVr

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote