How should I set up this c++ problem? I don't need it solved for me but a point in the right direction would be nice

你。 提交于 2020-11-29 19:05:36

问题


Here's the question I've been given:

Create a 4X3 integer array and fill it, column by column using loops, with the odd numbers starting with 1. In a separate, one dimensional array, store the average of each column of the 4X3 array. Output the 4X3 array (as a 4X3 array) and output the average of each column underneath each column. Label these as the average.

I just learned that I can make an array like this: N[4][3], but should I even do that here? I feel like setting up an array for each range: 1-4, 5-8 & 9-12, would work better so I can average them at the end.

I'm unfamiliar with multidimensional arrays, so please let me know if this is where I should start (I realize this isn't my idea, where I split them up that I mentioned earlier. I'm still unsure about this, in case you can't tell).

int X, N[3][4]={1};

for(X=1; X<12; X++) {
    N[X]= N[X-1]+2;
}

As far as I know, the tables are auto-filled, where each row is filled in order, rather than each column. How do I fill them in columns? I think that the splitting-them-up strategy would do this for me, correct me if I'm wrong.


回答1:


An important thing to keep in mind is that when you're using a for loop to access elements of a one-dimensional array defined like this for example for(int i=0; i<n; i++), i is the index of the array that you're using to access a specific element.

In the case of a two-dimensional array you would need 2 for loops (one nested inside the other) - the first will be for the index of the row, and another which will be for the index of the column. Here's an example of how you'd populate a two-dimensional array (iterating column by column) with dimensions MxN where all elements would be zero:

int matrix[M][N];
for(int j=0; j<N; j++) {
   for(int i=0; i<M; i++) {
       //j is an index for the column
       //i is an index for the row
       matrix[i][j] = 0;
   }
}

To populate it with odd numbers, you could use a separate variable initialized on 1, and increase its value by 2 for each new element in the matrix.



来源:https://stackoverflow.com/questions/65014791/how-should-i-set-up-this-c-problem-i-dont-need-it-solved-for-me-but-a-point

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!