Cpp I am tyring to this problem: Populate a 10 x 10 two dimensional array that c
ID: 3792523 • Letter: C
Question
Cpp
I am tyring to this problem:
Populate a 10 x 10 two dimensional array that contains random numbers between -100 and 100 (30 points).
Sort the two dimensional array from smallest to largest
Calculate the sum of all elements in the two dimensional array
Calculate average of two dimensional array
Get min and max of two dimensional array
Calculate median of two dimensional array
How I canfix this code to the median at the end of this code?
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
#include <time.h>
#define MAX 10
using namespace std;
int ranged_rand(int min, int max) {
return min + (int)((double)(max - min) * (rand() / (RAND_MAX + 1.0)));
}
int main() {
int arr[MAX][MAX];
int x, y, z, temp;
int sum=0;
int maxVal=0, minVal=0;
double avg=0.0, median = 0.0;
srand (time(NULL));
// generate random values
for( x=0; x<MAX; x++){
for( y=0; y<MAX; y++){
arr[x][y] = ranged_rand(-MAX, MAX);
arr[x][y] = ranged_rand(-MAX, MAX);
}
}
// sort array from smallest value to the largest
for( x=0; x<MAX; x++){
for( y =0; y<MAX; y++){
for(z = 1; z<MAX; z++){
if(arr[x][y]> arr[y][z-1]){
temp = arr[x][y];
arr[x][y]=arr[y][z-1];
arr[y][z-1]=temp;
}
}
}
}
// print out the array original generated values and sorted values
cout<<"Sn. org: sorted: ";
for( x=0; x<MAX; x++){
for(y=0; y<MAX; y++){
cout<<setw(3)<<x<<": "<<
setw(4)<<arr[x][y]<<" ";
}
}
// calculate the sum of the all elements
for( x=0; x<MAX; x++){
for( y=0; y<MAX; y++){
sum = sum + arr[x][y];
}
}
cout<<" Sum is "<< sum<< " ";
avg = double(sum)/MAX;
cout<<"Average is "<< avg << " ";
// get minimum value and maximum value
minVal = arr[0][0];
for( x=0; x<MAX; x++){
for( y=0; y<MAX; y++){
if(arr[x][y]<minVal)
minVal = arr[x][y];
}
}
cout<<"Min is "<<minVal<<" ";
// get maximum value
maxVal = arr[0][0];
for( x=0; x<MAX; x++){
for( y=0; y<MAX; y++){
if(arr[x][y]>maxVal)
maxVal = arr[x][y];
}
}
cout<<"Max is "<<maxVal<<" ";
median = double((arr[4][4] + arr[5][5]+ arr[][] + arr[][])) /4;
cout<<"Median is " << median << " ";
return 0;
}
Explanation / Answer
/*process to find median of a 2d array...
int aa[MAX*MAX], k=0;
for (x=0;x<MAX;x++)
{
for (y=0;y<MAX;y++)
{
aa[k++] = arr[x] [y] ;
}
}
median = aa[k/2];
if (k%2 == 0)
{
median = (median+aa[k/2-1] )/2;
}
//use above code for finding median of a 2d array