Nested Loops
Loops
for( int i=0; i< 5; i++ )
{
System.out.print( i );
}
What does this output?
Loops
for( int i=0; i< 5; i++ )
{
System.out.print( i );
}
> 01234
The loop iterates 5 times, so
the loop body executes 5 times
Loop Body
Nested Loops
for( int i=0; i< 5; i++ )
{
for(int j=0; j<5; j++)
{
System.out.print( j );� }
}
A loop inside a loop
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<5; j++)
{
System.out.print( j );� }
}
The loop iterates 5 times, so
the loop body executes 5 times
i |
0 |
1 |
2 |
3 |
4 |
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
Each time the outer loop iterates,
the inner loop iterates 3 times
The loop iterates 5 times, so
the loop body executes 5 times
What does this output?
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
What values will j have when i is 0?
i | j |
0 | |
1 | |
2 | |
3 | |
4 | |
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
What values will j have when i is 1?
i | j |
0 | 0 1 2 |
1 | |
2 | |
3 | |
4 | |
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
What values will j have when i is 2?
i | j |
0 | 0 1 2 |
1 | 0 1 2 |
2 | |
3 | |
4 | |
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
See the pattern?
i | j |
0 | 0 1 2 |
1 | 0 1 2 |
2 | 0 1 2 |
3 | |
4 | |
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
What does this loop output?
i | j |
0 | 0 1 2 |
1 | 0 1 2 |
2 | 0 1 2 |
3 | 0 1 2 |
4 | 0 1 2 |
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
When i is 0, the inner loop runs 3 times
> 012
When i is 0
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
When i is 1, the inner loop runs another 3 times
> 012012
When i is 1
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
When i is 2, the inner loop runs another, another 3 times
> 012012012
When i is 2
Nested Loops
for( int i=0; i<5; i++ )
{
for(int j=0; j<3; j++)
{
System.out.print( j );� }
}
> 012012012012012
Funsheet!