s0ck_IT
s0ck_IT

Reputation: 19

C++ for loop on 2d array

This is my 2d array:

int pay_scale[15][10] = 
{ { 18526, 19146, 19762, 20375, 20991, 21351, 21960, 22575, 22599, 23171},
{ 20829, 21325, 22015, 22599, 22853, 23525, 24197, 24869, 25541, 26213 },
{ 22727, 23485, 24243, 25001, 25759, 26517, 27275, 28033, 28791, 29549},
{ 25514, 26364, 27214, 28064, 28914, 29764, 30614, 31464, 32314, 33164},
{ 28545, 29497, 30449, 31401, 32353, 33305, 34257, 35209, 36161, 37113},
{ 31819, 32880, 33941, 35002, 36063, 37124, 38185, 39246, 40307, 41368},
{ 35359, 36538, 37717, 38896, 40075, 41254, 42433, 43612, 44791, 45970},
{ 39159, 40464, 41769, 43074, 44379, 45684, 46989, 48294, 49599, 50904},
{ 43251, 44693, 46135, 47577, 49019, 50461, 51903, 53345, 54787, 56229},
{ 47630, 49218, 50806, 52394, 53982, 55570, 57158, 58746, 60334, 61922},
{ 52329, 54073, 55817, 57561, 59305, 61049, 62793, 64537, 66281, 68025},
{ 62722, 64813, 66904, 68995, 71086, 73177, 75268, 77359, 79450, 81541},
{ 74584, 77070, 79556, 82042, 84528, 87014, 89500, 91986, 94472, 96958},
{ 88136, 91074, 94012, 96950, 99888, 102826, 105764, 108702,11640,114578},
{ 103672, 107128, 110584, 114040, 117496, 120952, 124408,127864, 1, 2}};

My goal is to std::cout in the same order it is displayed above so it prints each value in the first array pay_scale[0][n++] then moves onto pay_scale[1][[n++] then moves onto pay_scale[2][n++] etc. until it reaches pay_scale[14]

As of right now I just have:

for (int i = 0; i < 10; i++) {
     std::cout << "[" << pay_scale[n][i] << "]" << "\t";
}

And n = 0 I am having trouble indexing it without it jumping to the next array before it finishes the first one.

I must say I am new to cpp as I am sure you can see, any guidance is appreciated. Thank you!

Upvotes: 0

Views: 94

Answers (2)

Jake Freeman
Jake Freeman

Reputation: 1698

Why not use something more like this which loops through all the array:

for(int i = 0; i<15; i++)
{
    for(int n = 0; n<10; n++) cout<< "["<< pay_scale[i][n]<<"]\t";
    cout<<endl;
}

Hope this helps.

Upvotes: 0

Jive Dadson
Jive Dadson

Reputation: 17026

Here's the way the cool kids do it. :-)

for (const auto &row : pay_scale) {
    for (auto col : row) {
        std::cout << col << " ";
    }
    std::cout << "\n";
}

Upvotes: 2

Related Questions