In: Computer Science
I need to write a C++ program that will generate random numbers between the ranges of your own choice and within the random numbers, indicate the maximum, minimum and the average of the random numbers.
C++ code:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int generateRandom(int,int); // function declaration
void calculate(int[],int);
int main()
{
int ranNum,minRange,maxRange,i=0;
cout << "Enter the no.of random numbers : ";
cin >> ranNum;
int nums[ranNum];
cout << "Enter the range of random numbers : \n";
cin >> minRange >> maxRange;
cout << "Generated array : \n";
//while loop to generate random numbers by calling the
function
while(i!=ranNum){
nums[i] = generateRandom(minRange,maxRange); // calling
function
cout << nums[i] << " " ;
i++;
}
calculate(nums,ranNum); // for calculating avg, min & max
return 0;
}
void calculate(int nums[],int ranNum){
int max=nums[0],min=nums[0],avg,i=0,add=0;
for(i=0;i<ranNum;i++){
if(nums[i] < min){
min = nums[i];
}
else if(nums[i] > max ){
max = nums[i];
}
add = add+nums[i];
}
// printing the values
cout << "\nMIN : " <<min << " \t MAX : "
<<max << " \t AVG : " <<add/ranNum <<
"\n";
}
int generateRandom(int minRange,int maxRange){
int r = (rand() %
(maxRange-minRange)) + minRange; // random number generator with
ranges.
return r;
}
OUTPUT:

