2. Nested Loops
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.
3. Nested for Loops
When working with nested loops, the outer loop
changes only after the inner loop is completely
finished (or is interrupted.).
5. Infinite Loop
By using any repetition statements, make sure that
the loop will eventually terminate.
An infinite loop occurs when a condition always
evaluates to true and continues to execute
endlessly.
int product =0;
for (product = 0;product < 10;)
{ product = product * 2;
System.out.println(product);
}
7. Counter Controlled Loop
Know exactly how many times a set of statements
needs to be executed.
Output ? 1 3 5 7 9
int num =1;
while (num < 10)
{
System.out.print (num);
num = num +2;
}
Example 10:
8. Sentinel Controlled Loop
You might not know exactly how many times a set
of statements needs to be executed.
It uses a "special" or sentinel value to indicate that
the loop is to end.
This must be a value that doesn't occur normally in
the data.
9. Example 11 (complete program)
import java.util.Scanner;
class sentinelLoop {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an Integer, or -1 to stop: ");
int choice= input.nextInt();
while (choice!=-1)
{
System.out.println("INSIDE LOOPING");
System.out.print("Enter an Integer, or -1 to stop: ");
choice= input.nextInt();
}
System.out.println("Sentinel value detected. Good Bye.");
}
}
10. Example 11 ….
Enter an Integer, or -1 to stop: 2
INSIDE LOOPING
Enter an Integer, or -1 to stop: 5
INSIDE LOOPING
Enter an Integer, or -1 to stop: 0
INSIDE LOOPING
Enter an Integer, or -1 to stop: -1
Sentinel value detected. Good Bye.
OUTPUT?
11. Flag Controlled Loop
Use a boolean variable to control the loop
boolean found = false;
while (!found){
:
:
if(expression)
found = true;
}
12. Exercise 1:
What is the output of the following program?
public class LoopExercise1
{
public static void main (String args[])
{
int choice=1, total=0;
while (choice <4){
total = choice++;
System.out.print(total); }
}
}
13. Exercise 2:
What is the output of the following program?
public class LoopExercise2
{
public static void main (String args[]){
for (int number =2; number <20; number++)
{
number = number *2;
if (number <15)
System.out.println(number);}
}
}
14. Exercise 3:
How many times is the following loop body
repeated?
public class LoopExercise3 {
public static void main (String args[])
{
int i=1;
do {
if ((i % 2)== 0)
System.out.print(i);
i++;
} while(i<5);
}
}