0

I'm new to C++, and I've started to learn arrays. Here is my program on arrays:

#include <iostream>
using namespace std;
int main(){
    int arr[3][3];

    for (int i = 0; i<3; i++){

        for (int j = 0; j<3; j++){

            cout << "Enter " << j + 1 << " element of " << i + 1 << " row:";
            cin >> arr[i][j];

        }

    }

    for (int i = 0; i<3; i++){

        for (int j = 0; j<3; j++){
            cout << j + 1 << " element of " << i + 1 << "row:";

            cout << arr[i][j] << endl;


        }
    }
    system("pause");
    return 0;
}

I know that array's first index in C++ is zero. So, logically, an array arr[3][3]should have 4 * 4 = 16 elements, right? But practically, if I change 3 to 4 in my for cycles, I'll get out of range error. Why does it happen? Am I missing something? So, how much elemets are in arr[3][3]?

1
  • Oh sorry guys for such a question...It was pretty simple... You've made that absolutely clear for me right now! Commented Mar 18, 2015 at 16:32

3 Answers 3

1

So, logically, an array arr[3][3] should have 4 * 4 = 16 elements, right?

That is not correct.

For

int arr[3];

the valid element range is arr[0] - arr[2]. There are 3 elements.

For

int arr[3][3];

the valid element range is arr[0][0] - arr[2][2]. There are 9 elements.

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

Comments

1

When you declare an array, you write the number of elements(not counting 0, int arr[3] is an array with 3 elements. Only when you use them, you start counting from 0 (arr[2] = 666 accesses third element).

Comments

1

I know that array's first index in C++ is zero.

You are correct.

So, logicaly, an array arr[3][3]should have 4 * 4 = 16 elements, right?

Since first index is 0, arr[3][3] will be 0,1,2 rows and 0,1,2 columns. So, 9 elements enter image description here

Check out this link for tutorials on array (or C++ in general ☺ )

http://www.cplusplus.com/doc/tutorial/arrays/

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.