0

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();
    }
1
  • Every time to print the output, you need to tell the compiler that it is done executing one line and therefore needs to move to the next line. This will avoid over writing on the same line. So you just add <<endl; like cout<<a[i][j] + b[i][j]<<endl; Commented Jul 20, 2014 at 0:40

4 Answers 4

2

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;.

Sign up to request clarification or add additional context in comments.

Comments

1

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

cout<<"    ";

becomes

cout<<"\n";

Comments

0

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.

Comments

0

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.