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

In C++ Write a program that asks the user to enter the size for an array (greate

ID: 3806687 • Letter: I

Question

In C++

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: 1 5 3 5 4

Reversed array: 4 5 3 5 1

Explanation / Answer

#include <iostream>
#include <stdlib.h>
#include <malloc.h>

using namespace std;

void initializeArray(int *arr,int n){
   int i;
   for(i=0;i<n;i++){
       arr[i] = rand()%n + 1; //+1 is there because rand()%n would generate a random number among 0 to n-1
   }
}

void displayArray(int *arr,int n){
   int i;
   cout << "Array contains:";
   for(i=0;i<n;i++){
       cout << arr[i] << " ";
   }
   cout << " ";
}

void reverseArray(int *arr,int n){
   int i,temp;
   for(i=0;i<n/2;i++){
       temp = arr[i];
       arr[i] = arr[n-i-1];
       arr[n-i-1] = temp;
       // The above code is for Swapping required for reversing the array
   }
}

int main() {
   int i,n,*arr;
   cout << "Enter array size";
   cin >> n;
   arr = (int *)malloc(n*sizeof(int));
   initializeArray(arr,n);
   displayArray(arr,n);
   reverseArray(arr,n);
   displayArray(arr,n);
   return 0;
}