1 of 16

Nested Loops

2 of 16

Loops

for( int i=0; i< 5; i++ )

{

System.out.print( i );

}

What does this output?

3 of 16

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

4 of 16

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

5 of 16

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

6 of 16

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?

7 of 16

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

8 of 16

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

9 of 16

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

10 of 16

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

11 of 16

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

12 of 16

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

13 of 16

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

14 of 16

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

15 of 16

Nested Loops

for( int i=0; i<5; i++ )

{

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

{

System.out.print( j );� }

}

> 012012012012012

16 of 16

Funsheet!