Search code examples
c++loopsfor-loopnested-loops

Nested for-loops with numbers going down columns


So, obvious newbie here... My goal is to output a table with eight columns and ten rows with the numbers 1 through 80. This must be done using nested for loops (for an assignment). This is what I have so far:

int num = 1; //start table of numbers at one

for (int row = 0; row < 10; row++) //creates 10 rows
{
    for (int col = 0; col < 8; col++) //creates 8 columns
    {
        cout << num << "\t" ; //print each number
        num = num + 10;
    }

    cout << num;
    num++;

    cout << endl; //output new line at the end of each row
}

But my output should look like this:

1 11 21 31 41 51 61 71
2 12 22 32 42 52 62 72
...
10 20 30 40 50 60 70 80

Am I even in the right direction? How do I do this? Right now, only the first row is correct when I print it.


Solution

  • All you need to do is:

    int num = 1; //start table of numbers at one
    
    for (int row = 0; row < 10; row++) //creates 10 rows
    {
        for (int col = 0; col < 8; col++) //creates 8 columns
        {
             cout << num << "\t" ; //print each number
             num += 10;
        }
    num = row + 2;
    cout << endl; //output new line at the end of each row
    }
    

    EDIT: FIXED