Page 259 - PowerPoint Presentation
P. 259
CAVITE STATE UNIVERSITY
TRECE MARTIRES CITY CAMPUS
Department of Information Technology DCIT 111 - Advanced Programming
initialization; int i = 0;
do { do {
// body System.out.println(“Hi!”);
increment / decrement; i++:
} while (condition); } while (i<5);
The for loop
The last of the repetition statement is the for loop which provides a more convenient
way to handle counters in loops. Following the is syntax of a for loop.
for (initialization; condition; increment/decrement ) {
// body
}
The for header has three parts namely initialization, condition and
increment/decrement. The initialization part is used to declare and initialize loop control
variables or any other necessary variables before entering into the loop. The condition is
checked before executing the loop and the increment/decrement part is executed after each
time the body of the for loop is executed. Following code prints the numbers from 1 to 10 using
a for loop.
for (int i = 0; i<10; i++) {
System.out.println(i);
}
We generally use the identifiers i, j, k for loop control variables. We may also, declare
these variables outside the for loop.
We generally use the identifiers i, j, k for loop control variables. We may also, declare these
variables outside the for loop.
int i=0;
for (i= 0; i<=10; i++) {
System.out.println(i);
System.out.println(“The value of i was “ + i + “ when the loop condition
evaluated to false”);
}
The above code will display the statement “The value of i was 11 when the loop
condition evaluated to false” in addition to printing the number from 1 to 10.
The Nested for loop
The placing of one loop inside the body of another loop is called nesting. When you
“nest” two loops, the outer loop takes control of the number of complete repetitions of the inner
loop. While all types of loops may be nested, the most commonly nested loops are for loops.
Following is the syntax of nested for loop.
for (initialization; condition; increment/decrement ) {
// body
for (initialization; condition; increment/decrement) {
//body
}
}
35