Write a function that passes an array argument, getRandomNumbers, to get a pointer to an array of random numbers in the array. The function dynamically allocates an array, uses the system clock to seed the random number generator, populates the array with random values, and then returns a pointer to the array.
Function getRandomNumbers to generate a random array and return a pointer. int* getRandomNumbers(int num);
// The parameter indicates the number of numbers requested. The algorithm can be described as follows: Accept an array size as argument Dynamically allocate a new array that is the same size as the argument. White a loop to generate random numbers to the new array Return result as a pointer.
Here's what I have so far, but can't get it to work. please label what you did so I may disect it and learn from it
#include
#include
using namespace std;
int* getRandomNumbers(int *num,int & size);
int main()
{
int* num;
int size;
cout << "How big should the array be?" ;
cin >> size;
num = new int[size];
cout << num;
return 0;
}
int* getRandomNumbers(int *num,int &size)
{
srand(time(0));
for (int i = 0;i < size;i++)
{
num[i] = rand() % 50 + 1;
}
return num;
}
So, here's what that went wrong:
-> Header files iostream, stdlib.h and time.h were not
included.
-> After reading the input 'size', there is no call for the
function.
-> Also, I see that you're printing the address of num but not
the values in the array.
I've made the necessary changes for the program to work.
Code:
#include<iostream>//including required headers
#include<stdlib.h>
#include<time.h>
using namespace std;
int* getRandomNumbers(int *num,int & size);
int main()
{
int* num;
int size;
cout << "How big should the array be?" ;
cin >> size;
num = new int[size];
num = getRandomNumbers(num, size);//calling function
for(int i = 0; i < size ; i++)//printing values
cout << num[i] << " ";
return 0;
}
int* getRandomNumbers(int *num,int &size)
{
srand(time(0));
for (int i = 0;i < size;i++)
{
num[i] = rand() % 50 + 1;
}
return num;
}
Output:
Get Answers For Free
Most questions answered within 1 hours.