+ 1
C++ Array2D
Can someone explain on how to get the output? #include <iostream> using namespace std; int main() { int array[5][4]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; //start looping over rows for (int i=0;i<4;i++) { cout<<array[0][i]<<"\t"; } cout<<endl; for (int j=1;j<5;j++) { for(int k=0;k<4;k++) { cout<<array[j][k]<<"\t"; } cout<<endl; } cout<<endl; return 0; }
9 ответов
+ 5
#include <iostream>
using namespace std;
int main()
{
int array[5][4] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
for(int row = 0; row < 5; row++)
{
for(int col = 0; col < 4; col++)
{
cout << array[row][col] << " ";
}
cout << endl;
}
cout<<endl;
return 0;
}
This code will generate the same output.
The outer loop is used to control the iteration over rows and the inner loop is used to control the iteration columns.
Think of it like the coordinates
rows = y-axis and columns = x-axis.
+ 3
You're welcome Leon S Han 勇面, no master, a friend : )
+ 2
* For 2 dimension array we have a couple of index brackets used to refer to a certain cell, a cell is a value in a certain row and column.
Like in your code, the first loop iterates the columns of the first row:
for(int i = 0; i < 4; i++)
{
cout << array[0] [i] << " ";
}
Notice the first [0] refer to the row index, and second [i] refer to column index (always remember indexes starts from zero)
* Next it's a nested loop.
The outer loop iterates the rows, starting from the second row, hence variable <j> initialized with 1.
The inner loop iterates the columns of the row currently referred to by <j>, in the inner loop row index is represented by [j] and column index represented by [k].
for (int j = 1; j < 5; j++) // outer
{
for(int k = 0; k < 4; k++) // inner
{
cout << array[j][k] << " ";
}
cout << endl;
}
Hth, cmiiw
+ 2
Thanks a lot , all masters
+ 1
I guess you made a tiny mistake in array initialization here, you probably were looking for a 5 rows array with 4 columns instead of a 1 row with 20 columns : )
#include <iostream>
using namespace std;
int main()
{
// Here's how you make multidimensional
// array, this has 5 rows, with 4 columns
// each row.
int array[5][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16},
{17,18,19,20}
};
for (int i = 0; i < 4; i++)
{
cout << array[0][i] << " ";
}
cout << endl;
for (int j = 1; j < 5; j++)
{
for(int k = 0; k < 4; k++)
{
cout << array[j][k] << " ";
}
cout << endl;
}
cout << endl;
return 0;
}
Hth, cmiiw
0
Ya ,i try both of the methods in visual 6.0, but I manage to get the same output .
0
Now , I don't understand about the using of for to display the output in row and columns 🤣
0
Which part of the loop that you don't understand? have you reviewed the chapter on for loops?
0
The "For" parts