+ 1
I was going through my notes and realized that we were never show how to iterate through a multidimentional array. How's it done
My code below works to print all the numbers, but I want to have them in rows and columns. Run my code and you will see this is not what I want. #include <iostream> using namespace std; int main() { int myArr[2][3] = {{2, 3, 4}, {8, 9, 10} }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << myArr[i][j] <<endl; }}; return 0; } Any ideas guys on how to make this come out looking like a table with 2 rows and 3 columns?
3 ответов
+ 3
//just learn more about how loops work..
#include <iostream>
using namespace std;
int main()
{
int myArr[2][3] = {{2, 3, 4}, {8, 9, 10} };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << myArr[i][j] << " ";
}
cout<<endl; //to add new line after inner loop
}
return 0;
}
+ 1
Ah, clever. Put the cout statement outside of the for loop's protection. I was just about to try making two different for loops, each with it's own cout statement, but this will save time and space. Thanks for the assist.
0
Correction to my last statement in case anyone reads this and is confused. I meant that the endl statement is outside the for loop's protection.