0

I have a 2d array and I want to know how do you set the first value so if my array was

int array[a][b] = int[10][10];

How would you access index 'a' in a for loop?

This is my simple code that I am working on thanks in advance

int[][] timesTable = new int[12][12];

for(int i = 0; i < timesTable.length; i++){
    timesTable[i][i] = i + 1;//can't set the first index with this value
    System.out.println(timesTable[i]);
}
0

2 Answers 2

3

I hope you are not putting the "a" and "b" in the array declaration.

int array[][] = int[10][10];

A 2D array is array of arrays. The index "a" or what you are trying to set is another array.

 timesTable[i][i] = i + 1;//can't set the first index with this value

The above can be written like this:

timesTable[i] = {1,2,3};// puts another array at index i
Sign up to request clarification or add additional context in comments.

Comments

3

You access your array using [], which you'll need to do n times for an n-dimensional array if you're trying to access a particular element.

If you're simply trying to set the first element, then you can do:

array[0][0] = 100; // some number

If you want to iterate over each element in the entire 2d array, you'll need 2 loops, one for each dimension, like so:

for ( int i = 0; i < array.length; ++i ) {
    for ( int j = 0; j < array[i].length; ++j ) {
        array[i][j] = i + j; // or whatever you want to set the elements to
        System.out.println( array[i][j] );
    }
}

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.