Page 240 - IT-802_class_12
P. 240
Semicolons separate the three parts of a for loop:
Ð ÐThe initial_value initializes the value of the loop counter.
Ð ÐThe test_condition tests whether the loop should be executed again.
Ð ÐThe loop is exited when the test condition fails. The step updates the counter in each loop iteration.
For example, consider the following loop that prints the square of numbers from 1 to 5:
for (int number = 1; number<= 5; ++number)
{
System.out.print(“Square of “+ number);
System.out.println(“ = “+ number*number);
}
The variable number is set to 1 when the loop starts. The test condition then checks whether the loop variable,
number=5, is equal to 5. If it is, the loop’s body is run, which prints the square of one. The count is then increased by
one step. The test condition is checked once more to see if the body should be executed. If it is less than 5, the variable
number’s square is printed. The loop is terminated when the number reaches 5. The squares of numbers from 1 to 5
are the program’s output.
In English, we read the loop above as follows: for number is equal to 1; number is less than or equal to 5; execute the
body of the loop; increment number; loop back to the test condition. The loop given above counts up the loop index. It
is an incrementing loop. We can also count down in a loop for a decrementing loop. The following decrementing loop
will execute 5 times.
for (int number = 5; number >= 1; number = number-1)
{
System.out.print(“Square of “ + number);
System.out.println(“ = “ + number*number);
}
The loop index can be incremented or decremented by any value, not just 1. The following loop increments the loop
index by 2. It displays all odd numbers between 1 and 20.
for ( int count = 1; count <= 20; count = count +2)
{
System.out.println(count);
}
The loop index can begin with any value, not necessarily 1. The following loop also iterates 5 times and prints number
from 5 to 9.
for ( int count = 5; count < 10; count++)
{
System.out.println(count);
}
The counter in the loop iterates with count values – 5,6,7,8,9 for a total of five times.
Notice that the test condition is count < 10 instead of count <= 10. If it was the latter, the loop would have iterated 6
times for loop index count as 5,6,7,8,9,10.
238 Touchpad Information Technology-XII

