Help with 2D arrays?

closed account (EApGNwbp)

#include <iostream>
using namespace std;

How can I print the whole rows and columns instead of only outputting one number?

Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()

{

    
    int sally [3] [4] = {{1,5,8,10},{3,5,6,9}, {7,9,4,5}};
    // 1, 5, 8, 10
    // 3, 5, 6, 9
    // 7, 9, 4, 5
    
    //column
    // O, 1, 2, 3
    cout << sally [1] [2];
    return 0;
}
Last edited on
You'll need to iterate through the array using a nested for loop.

1
2
3
4
5
6
7
8

for(int x = 0; x < 3; x++)
    {
       for(int y = 0; y < 4; y++)
            {
               std::cout<<sally[x][y]<<" ";
            }
     }


The simplest way is to use the range-based for statement. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <iomanip>

int main()
{
    int sally [3] [4] = {{1,5,8,10},{3,5,6,9}, {7,9,4,5}};
    // 1, 5, 8, 10
    // 3, 5, 6, 9
    // 7, 9, 4, 5
    
    //column
    // O, 1, 2, 3
    for ( const auto &row : sally )
    {
        for ( int x : row ) std::cout << std::setw( 2 ) << x << ' ';
        std::cout << std::endl
    }

    return 0;
} 
Last edited on
Topic archived. No new replies allowed.