Printing 2D arrays?

I have encountered a problem with printing 2D arrays. Here is my code, any help will be greatly appreciated.

#include<iostream>

using namespace std;

int main()
{
int NumRow, NumColumn;
int anArray[2][2] = {{1,2},{3,4}};
for (int N_column = 1; N_column < NumColumn; N_column++)
{
    for (int N_row = 1; N_row < NumRow; N_row++)
{
    cout << anArray[N_row,N_column];
}
}
return 0;
}

Answers


3 problems:

  1. Array indexes start at 0.
  2. NumColumn, NumRow are uninitialized.
  3. wrong syntax [y,j], use [i][j]

Try like this:

...
int NumRow = 2, NumColumn = 2;
int anArray[2][2] = {{1,2},{3,4}};
for (int N_column = 0; N_column < NumColumn; N_column++)
{
    for (int N_row = 0; N_row < NumRow; N_row++)
    {
         cout << anArray[N_row][N_column];
    }
}
...

You declare

int NumRow, NumColumn;

but you never assign a value to them. Use

int NumRow = 2, NumColumn = 2;

instead. Also, C-arrays start at 0, not at 1, so you must update your for-loops as well:

for (int N_column = 0; ...

    for (int N_row = 0; ...

Last, change the output statement, as multidimensional arrays need to be reached in a different way:

cout << anArray[N_row][N_column];

There are few issues in your code:

1st: You declare NumRow, NumColumn but use them without initializing them before which cause to Undefined Behaviour.

Solution: Initialized them

NumRow = 2;
NumColumn = 2;

2nd: Array syntax in the following line-

cout << anArray[N_row,N_column];

it should be

cout << anArray[N_row][N_column];

3rd: C++ arrays are zero indexed, so you should start initializing the loop control variables like following:

for (int N_column = 0; N_column < NumColumn; N_column++)
{                   ^^^
    for (int N_row = 0; N_row < NumRow; N_row++)
    {               ^^^^
        //...

Need Your Help

Google Docs Pixels to Inches

javascript google-docs google-docs-api

Is anyone aware of the formula google docs use to convert pixels to inches?

How to send date and time to SQL using java

java sql date time

I am calling a stored procedure in a database.