Asad
Asad

Reputation: 1

2d array addition in c++

i am trying to add two 2D arrays in C++ with my following code by i am getting output as this 333 333, but i want out as 2 rows

    { 
        int a[2][3], b[2][3], i , j;

        cout<<"First Matrix"<<endl;
    for (int i=0; i<2; i++)
    {
        for (int j=0; j<3; j++)
        {
    cin>>a[i] [j];
        }
    }
    cout<<"Second Matrix"<<endl;
            for(int i=0; i<2; i++)
    {
        for (int j=0; j<3; j++)
        {
        cin>>b[i][j];
        }
    }
    for (int i=0; i<2; i++)
    {
        for (int j=0; j<3; j++)
        {
            cout<<a[i] [j] + b[i] [j];
        }
        cout<<"    ";
    }
    cout<<endl;

    _getch();
    }

Upvotes: 0

Views: 407

Answers (4)

user3478972
user3478972

Reputation:

Last for loop is wrong. You have to move cout's.

for (int i=0; i<2; i++)
    {
        for (int j=0; j<3; j++)
        {
            cout<<a[i] [j] + b[i] [j];
            cout<<"    ";
        }
        cout<<endl;
    }

Also your variables i and j are unused because you are declaring new ones in for loops with int i=0; and int j=0;.

Upvotes: 2

Guilherme
Guilherme

Reputation: 453

Replace the last piece of code by this:

for (int i=0; i<2; i++)
{
    for (int j=0; j<3; j++)
    {
        cout<<a[i] [j] + b[i] [j] << ' ';
    }
    cout<< "\n";
}
cout << "\n";

Upvotes: 0

aruisdante
aruisdante

Reputation: 9115

You don't put any newlines in your code, so of course it won't print out on a new line. replace cout<<" "; with cout<<std::endl; and you should get each row on a new line.

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

How about changing the line that prints spaces to print a newline?

cout<<"    ";

becomes

cout<<"\n";

Upvotes: 1

Related Questions