1

I am trying to print a 2d array like this.

1,2

3,4

5,6

7,8

until 20

and this is the code

#include <iostream>
using namespace std;
int main()
{
    int A[10][2]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

    for(int i=0;i<10;i++)
        for(int j=0;j<2;j++)
        {
            cout<<A[i][j]<<" ";
        }
        cout << endl;



}

But everytime it prints it prints them in straight line , like 1 2 3 4 5 6............. What could I be doing wrong?

Ahsen
  • 13
  • 3
  • 3
    Turn on compiler warnings. Does it say that your code might be wrong? Something to do with indentation? – cigien Jun 28 '20 at 12:20
  • 1
    You are not doing what you think you are doing: you are essentially doing this: `for(int i=0;i<10;i++) { for(int j=0;j<2;j++) { cout< – dfrib Jun 28 '20 at 12:24
  • 1
    When you don't use braces after `for` loop, then only the next line will be in `for`'s scope. So use braces after the first `for` and put the second `for` and the `cout << endl;` in the first `for`'s scope. – Farbod Ahmadian Jun 28 '20 at 12:25
  • `int A[10][2] = { {1, 2}, {3, 4 }, {5, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 14}, {15, 16}, {17, 18}, {19, 20} };` correct way to initialize your array – pvc Jun 28 '20 at 12:28
  • Okay , I added the second "for" in braces and I got the desired result. But why does the endl; doesn't get iterated when I put it in braces along the second for? Why '2' doesn't get on the second line after '1' ? – Ahsen Jun 28 '20 at 12:36
  • Now it looks like this for(int i=0;i<10;i++) {for(int j=0;j<2;j++) cout< – Ahsen Jun 28 '20 at 12:37
  • Outside of readability indentation means *nothing* to a C++ program. Indent your code properly, then look in the original and you'll see how that `cout << endl;` was dangling out there on its own, outside of *both* loop bodies. – WhozCraig Jun 28 '20 at 12:38
  • @WhozCraig Nitpicking, but indentation _can_ have meaning: in this particular example some compilers will use the indentation to infer that OP actually made a mistake, and can explicitly emit a warning for the `cout` line, pointing out that it is not in scope of the first for loop but that indentation of the program hints that it was actually intended to be within the for loop’s scope. – dfrib Jun 28 '20 at 13:04
  • @pvc It's clearer to initialize it like you suggested but OP:s initialization is just as correct. – Ted Lyngmo Jun 28 '20 at 20:59

1 Answers1

1

Hey there you forgot to add {} after first for loop. Here's solution

#include <iostream>
using namespace std;
int main()
{
    int A[10][2]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};

    for(int i=0;i<10;i++)
    {
        for(int j=0;j<2;j++)
        {
            cout<<A[i][j]<<" ";
        }
        cout << endl;   
    }
}
john
  • 85,011
  • 4
  • 57
  • 81
WhiteSpidy.
  • 1,107
  • 1
  • 6
  • 28