1

I'm really struggling to comprehend nested for loops and so have done as followed:

    int arr[][] = new int[10][3];
    int i, j;

    arr[0][0]=21;  
    arr[1][0]=41;  
    arr[2][0]=61;  
    arr[3][0]=81;  
    etc.

... to get the following output:

21 21 21
41 41 41
61 61 61
81 81 81
etc.

I understand this is highly inefficient, so have attempted to construct a nested for loop which clearly doesn't work:

for(i=21;i<81;i+=20)
        {
           for(j=0;j<arr[i].length;j++)
           {
              arr[i][j] = i+j;
           }
        }

A guide in the right direction is greatly appreciated. Thanks.

1
  • Looks like a nice pair of nested for loops to me. What exactly is your problem? Commented Oct 30, 2018 at 2:26

3 Answers 3

2

This is what I tried, seem it match with your requirement, you can check it.

    int arr[][] = new int[10][3];
    int i, j;
    int value = 21;
    for(i =0; i <10;i++) {
        for(j = 0; j <3; j++) {
            arr[i][j] = value;
        }
        value +=20;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

The formula you are interested in seems to be ((i + 1) * 20) + 1 which will give you the value at the correct zero based index. Like,

int[][] arr = new int[10][3];
for (int i = 0; i < arr.length; i++) {
    int c = ((i + 1) * 20) + 1;
    for (int j = 0; j < arr[i].length; j++) {
        arr[i][j] = c;
    }
}
System.out.println(Arrays.deepToString(arr));

Outputs (formatted for post)

[[21, 21, 21], [41, 41, 41], [61, 61, 61], [81, 81, 81], 
 [101, 101, 101], [121, 121, 121], [141, 141, 141], 
 [161, 161, 161], [181, 181, 181], [201, 201, 201]]

Note we could use Arrays.fill(int[], int) to fill the array too. Like,

for (int i = 0; i < arr.length; i++) {
    int c = ((i + 1) * 20) + 1;
    Arrays.fill(arr[i], c);
}

Comments

0

I think this is what you might be looking for. Hope it helps

int minValue = 21, increment = 20;

int arr[][] = new int[4][3];

for(int i = 0; i < arr.length; i++)
{
  for(int j = 0; j < arr[i].length; j++)
  {
    arr[i][j] = minValue;
  }
}

minValue += increment;

4 Comments

what is the purpose of maxValue = 81 ?
I don't think j[i].length in the inner for loop will compile.
Also i and j are undefined
Thanks for all the comments. Correction has been made to the code.

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.