Muhammad Hamza
Muhammad Hamza

Reputation: 21

2d array error: row index printing

Actually i was tying to print 2d array by user. Then adding the number row wise. I don't know how to print row index number. The code is:

int arr[3][3];
int sum = 0;

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
        cin >> arr[i][j];
}

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


for (int x = 0; x < 3; x++)
{
    for (int y = 0; y < 3; y++)

        sum += arr[x][y];
    cout << "Row: " << arr[x] << "addition is:" << sum << endl;
    sum = 0;
}

In 2nd last row arr[x] print the address. If i use arr[x][y] it tells ( 'y' is undefined). why 'y' is undefined ? And kindly someone tell me how to add numbers diagonally...?

Upvotes: 1

Views: 67

Answers (3)

Dannyu NDos
Dannyu NDos

Reputation: 2508

'y' is undefined because it went out of its scope.

To add numbers diagonally, you can do:

sum = 0;
for (int i = 0; i < 3; ++i)
    sum += arr[i][i];

Upvotes: 1

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123263

I would suggest you to use brackets on loops always. This

 for (int y = 0; y < 3; y++)
    sum += arr[x][y];
 cout << "Row: " << arr[x] << "addition is:" << sum << endl;

is equivalent to

 for (int y = 0; y < 3; y++) {
    sum += arr[x][y];
 }
 cout << "Row: " << arr[x] << "addition is:" << sum << endl;

and outside of the loop y is not declared. You probably wanted

for (int y = 0; y < 3; y++) {
   sum += arr[x][y];
   cout << "Row: " << arr[x] << "addition is:" << sum << endl;
}

Further, you say you want to print the row index, which is either x or y, but not arr[x][y] which is the element at index [x][y].

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409442

Well arr[x] is an array, which decays to a pointer to its first element. So when you print arr[x] you are in fact printing &arr[x][0].

I assume you want to print x only:

cout << "Row: " << x << ...

Upvotes: 2

Related Questions