displaying a simple array
task: to display array first column by column then row by row.
?: is this correct?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <iostream>
using namespace std;
int main()
{
int nums[2][4] = { { 17, 24, 86, 35 },
{ 23, 36, 10, 12 } };
int row = 0;
int column = 0;
//display column by column
while (column < 4)
{
for (int row = 0; row < 2; row++)
{
cout << "Numbers (column): " << nums[row][column] << endl;
}
column++;
}
cout << endl;
//display row by row
while (row < 2)
{
for (column = 0; column < 4; column++)
{
cout << "Numbers (row): " << nums[row][column] << endl;
}
row++;
}
cout << endl;
system("pause");
return 0;
} //end of main function
|
Obligatory http://www.cplusplus.com/forum/beginner/1988/ and http://www.cplusplus.com/forum/articles/11153/ .
Why are you using a
while
loop and then a
for
loop? Why not two
for
loops?
1 2 3 4 5 6 7 8 9 10 11
|
for (std::size_t column = 0; column < MAX_COLUMNS; column++) {
for (std::size_t row = 0; row < MAX_ROWS; rows++) {
// by column
}
}
for (std::size_t row = 0; row < MAX_ROWS; rows++) {
for (std::size_t column = 0; column < MAX_COLUMNS; column++) {
// by row
}
}
|
Also, instead of using magic numbers, define constants like
MAX_ROWS
and
MAX_COLUMNS
and reference those instead. That improves code readability.
Last edited on
The instructions say "complete the program using a while statement in the outer loops and a for statement in the nested loops."
Topic archived. No new replies allowed.