This site requires JavaScript, please enable it in your browser!
Greenfoot back
Sauravbasyalking12
Sauravbasyalking12 wrote ...

2020/9/27

Nested loops

Sauravbasyalking12 Sauravbasyalking12

2020/9/27

#
Hi can you provide me the nested loops examples and its explanation
RcCookie RcCookie

2020/9/27

#
Do you mean a specific example? I could give you this example: You want to check if any value in a two dimensional boolean array is true you want to print something:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
boolean[][] values = {{false, false}, {false, false}, {true,false}};
 
// option a: normal for loop
for(int i=0; i<values.length; i++) {
    for(int j=0; j<values[i].length; j++) {
        if(values[i][j]) System.out.println(i+“/„+j+“ is true“);
    }
}
 
// option b: foreach loop
for(boolean[] row : values) {
    for(boolean value : row) {
        if(value) System.out.println(“A value is true“);
    }
}
This however requires you to know how loops and arrays work. Do you?
danpost danpost

2020/9/27

#
Sauravbasyalking12 wrote...
Hi can you provide me the nested loops examples and its explanation
A nested loop is just one loop inside of another. Most often, I believe, they are used to iterate over a 2D array. Other times might be to iterate over a 1D array multiple times. It is not required to have a literal array; just having a range of values or a group of objects is sufficient. Example A: coloring a checkerboard
1
2
3
4
5
6
7
for (int y=0; y<8; y++) // for each row
{
    for (int x=0; x<8; x++) // for each square in row
    { // color square
        colorSquare(x, y, (new Color[] { Color.WHITE, Color.BLACK })[(x+y)%2]); // method not given
    }
}
Example B: sort an integer array (low to high)
1
2
3
4
5
6
7
8
9
for (int i=1; i<array.length; i++) // for all but first value
{
    int n=i;
    while (n>0 && array[n] < array[n-1]) // while value is swap-able and needs swapped
    { // push forward
        swap(array, n-1, n); // method not given
        n--;
    }
}
Example C: applying gravitational forces between objects
1
2
3
4
5
6
7
8
9
10
11
List sms = getObjects(SmoothMover.class);
for (int j=0; j<sms.size()-1; j++) // for each listed mover
{
    SmoothMover smA = (SmoothMover)sms.get(j);
    for (int i=j+1; i<sms.size(); i++) // and for each subsequent mover
    {
        SmoothMover smB = (SmoothMover)sms.get(i);
        smA.applyGravity(smB); // apply force of one on another
        smB.applyGravity(smA); // and apply force of the other on the one
    }
}
Sauravbasyalking12 Sauravbasyalking12

2020/9/30

#
thank you so much both of you
You need to login to post a reply.