+ 1

Average of 2d array

I need to create an average of rows and columns of a 2d array with random numbers. I have created the nested for loop, but the output is 3 numbers like this -2.345e^4321(not the exact output, but the range is 0 -100 integers, so a double average shouldn't get this output. I apologize, I was in another class. Here's code, even though I did work on it a bit, but now I get the averages in the range, but now I don't have random numbers: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { srand(time(NULL)); const int rows =3; const int cols =3; int ranInt[rows][cols]; int sum = 0; double average =0; for(int row = 0; row < rows; row++){ for(int col =0; col < cols; col++){ sum+= ranInt[rows][cols]; // cout << sum; } double average = sum/(cols*rows); cout << "Average: " << average<<endl; } return 0; }

8th Nov 2018, 10:23 PM
dominic smith
dominic smith - avatar
4 Answers
+ 11
for random numbers you need to use rand function Here's a formula for it to generate random values in a range int num = rand() % (maxVal - minVal + 1) + minVal where maxVal and minVal are maximum and minimum values respectively
9th Nov 2018, 6:30 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 5
Please, can you show us your attempt !? 👍😉
8th Nov 2018, 10:39 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 5
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main(){ const int rows = 3; const int cols = 3; int ranInt[rows][cols]; int sum = 0; srand(time(NULL)); for(int row = 0; row < rows; row++){ for(int col = 0; col < cols; col++){ /* The array's elements are not yet assigned a value, if you print them on screen you'll see that they contain garbage values. Use rand() function to assign them random values, as it had been suggested earlier. Use <row> & <col> to refer to an array element by index, these are the designated loop iterators, not <rows> and <cols> */ ranInt[row][col] = rand() % 101; sum += ranInt[row][col]; } } /* Calculate the <average> here, outside the loops */ double average = sum / (cols * rows); cout << "Average: " << average << endl; return 0; } Hth, cmiiw
9th Nov 2018, 4:50 PM
Ipang
+ 3
So you want to average all the values in the 2D array? Hint: A 2D array is just a list (like a 1D array). 2 rows of four columns is just 8 elements.
9th Nov 2018, 12:40 AM
non