Here is the complete code in C++.
rand() function is used to generate the random number and it is stored in an integer array.
To find the average,the sum of all elements in the array is divided by number of array elements.
To find the minimum and maximum, the array is sorted in ascending order using Linear sort technique.After sorting, the minimum value will be present at first index of array(arr[0]) and maximum element will be present at the last index of array(arr[n-1]).
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
long long int sum=0; /* Initialize sum as 0;Sum is declared as long long int as the total of all random numbers might exceed the range of INT */
cout<<"Enter the number of elements"<<endl; // taking number of integers input from user
cin>>n;
srand(time(0));
int arr[n];
for(int i=0;i<n;i++){
int temp=rand()%INT_MAX; // generates a random number upto INT_MAX
arr[i]=temp; // Stores the random number into array
sum+=arr[i]; // Store the sum of the elements to find the average
}
int min=INT_MAX,max=INT_MIN,avg;
cout<<"Average = "<<(double)sum/n; // explicitly type casted to double because average might contain a decimal value also
// Sorting the elements of the array in ascending order
for(int i=1;i<n;i++)
{
if(arr[i-1]>arr[i])
{
int temp=arr[i-1];
arr[i-1]=arr[i];
arr[i]=temp;
}
}
cout<<"Minimum = "<<arr[0]<<endl; // First element of array stores the minimum value
cout<<"Maximum = "<<arr[n-1]<<endl; // Last element of array stores the maximum value
}
Get Answers For Free
Most questions answered within 1 hours.