Write a program to ask the user for a positive integer n, allocate enough space
ID: 3879277 • Letter: W
Question
Write a program to ask the user for a positive integer n, allocate enough space on the heap for an array of integers that has n elements and then fill that array with random values using the function rand( ). Pass the array to a function called find_max that will return the index of the largest element of your array.
Your main program should print the index of the largest element of the array on the screen.
Remember to free up memory before terminating the program.
The function rand() is a library function that returns a value between 0 and RAND_MAX and can be called to get random values for each element of your dynamic array.
Explanation / Answer
#include<iostream>
#include<cstdlib>
using namespace std;
int find_max(int a[],int n)
{
int max=0;
for(int i=0;i<n;i++)//finding position of max value
{
if(a[i]>a[max])max=i;
}
return max;//returning the position of a max value
}
int main()
{
int n;
cout<<"Enter a number size of array:";
cin>>n;//prompting input
int *array = new int[n];//creating memory with size n...dynamically
int rand_max=10000;
for(int i=0;i<n;i++)
{
array[i] = rand()%rand_max;//generating random number (between 0-rand_max)and assigning to array...
}
int position = find_max(array,n);
cout<<"The position of max value is :"<<position<<endl;
delete [] array;//deleting array
return 0;
}
output:
Enter a number size of array:10
The position of max value is :7
Process exited normally.
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.