Sebastian
Sebastian

Reputation: 71

Printing a simple 2x3 matrix

I'm very new to C++ and I have a little task of printing a simple 2x3 matrix consisting of just 0s. However despite some attempts I cannot figure out how to code to print the matrix correctly. This is my code:

#include <stdlib.h>
#include <iostream>
using namespace std;

int main()
{
    int n_rows = 3;
    int n_cols = 2;

    for (int a = 0; a < n_cols; a++)
        for (int b = 0; b < n_rows; b++)
            cout << "0" << " ";
            cout << "\n";

    return 0;
}

The output of my code is:

0 0 0 0 0 0 

The output should actually be this:

0 0 0
0 0 0

Could anyone describe how to get the correct output? Thanks.

Upvotes: 1

Views: 582

Answers (2)

Syed Arsalan Hussain
Syed Arsalan Hussain

Reputation: 409

You are not breaking the line in the second loop. Your code is breaking the line in the first loop.

#include <stdlib.h>
#include <iostream>
using namespace std;

int main()
{
    int n_rows = 3;
    int n_cols = 2;

    for (int a = 0; a < n_cols; a++){
        for (int b = 0; b < n_rows; b++)
            {
               cout << "0" << " ";
            }
             cout << "\n";
           } 

    return 0;
}

Upvotes: 5

MikeCAT
MikeCAT

Reputation: 75062

You have to add {} for the for (int a = 0; a < n_cols; a++) loop to have cout << "\n"; executed in each iteration, not after executing the loop.

#include <stdlib.h>
#include <iostream>
using namespace std;

int main()
{
    int n_rows = 3;
    int n_cols = 2;

    for (int a = 0; a < n_cols; a++)
    { // add this
        for (int b = 0; b < n_rows; b++)
        { // this is not necessary but recommended
            cout << "0" << " ";
        } // this is not necessary but recommended
        cout << "\n"; // also using proper indentation is recommended
    } // add this

    return 0;
}

Upvotes: 3

Related Questions