Iteration is one of the most key elements of programming. There are many situations where it is desirable to perform multiple tasks numerous times. For example imagine an algorithm which works out the following pattern.

2,4,6,8,10,12,14,16.

Clearly this is just the two times table. We want an algorithm which will print out all the numbers in the two times table for the first n terms as shown in the table below.

N

1

2

3

4

5

6

7

8

9

2N

2

4

6

8

10

12

14

16

18

So the algorithm, given the value 4, should produce 2,4,6,8. Given the value 6 should produce 2,4,6,8,10,12 and so on. As the number N could be any number, it is impossible to list out all of the instructions. Here is what the code may look like if we tried.

  1. IF (N => 1) System.out.println( 2 );
  2. IF (N => 2) System.out.println( 4 );
  3. IF (N => 3) System.out.println( 6 );

 

Given N as 1,2 or 3 this algorithm will produce the correct result (try it!). However what about for N=4? We could add another IF statement but then we will be faced with the same problem for N=5. Clearly this is not a good algorithm. What we can do is use a special construct known as a FOR loop.

A FOR has the form

  1. FOR ( <Initial value>; <condition>; <increment>){
  2. // instructions here
  3. }

 

The initial value is the start of the loop, the first value the loop will act on. The condition is when we stop the loop and increment says the step or what value we change the initial value to after each iteration.

 

  1. for (i = 1; i<=n; i = i + 1){
  2. System.out.println (i * 2);
  3. }

This looks much simpler. Let's run through a trace.

 

START

N = 4

println I=1 * 2 First iteration

println I=2 * 2 Second iteration

println I=3 * 2 Third iteration

println I=4 * 2 Forth iteration

STOP

 

Given N as 4:- The first iteration the variable I becomes 1. The next l line says println I * 2, so that becomes println 1 * 2. We then come to the end of the block. At this point you must check if the condition has been satisfied. It does the check I <= N. 1 is less thanl 4 so it goes back to the start of the for loop and adds 1 to I. So the next time we get to println I * 2 we will run println 2 * 2.

next for loops >>

 
Basics
Menu
Search