While Loop
While Loop
(loops)
Loops – While, Do, For
• Repetition Statements
- While
- Do
- For
2
Repetition Statements
while ( condition )
statement;
• If the condition is true, the statement is executed
• Then the condition is evaluated again, and if it is still true, the statement is
executed again
• The statement is executed repeatedly until the condition becomes false
4
Logic of a while Loop
condition
evaluated
true false
statement
5
The while Statement
int count = 0;
while (count < 2)
{
System.out.println("Welcome to Java!");
count++;
}
• If the condition of a while loop is false initially, the statement is never
executed
• Therefore, the body of a while loop will execute zero or more times
6
animation
Initialize count
int count = 0;
while (count < 2)
{
System.out.println("Welcome to Java!");
count++;
}
7
animation
8
animation
int count = 0;
while (count < 2)
{
System.out.println("Welcome to Java!");
count++;
}
9
animation
Increase count by 1
int count = 0; count is 1 now
while (count < 2)
{
System.out.println("Welcome to Java!");
count++;
}
10
animation
11
animation
int count = 0;
while (count < 2)
{
System.out.println("Welcome to Java!");
count++;
}
12
animation
int count = 0;
while (count < 2)
{
System.out.println("Welcome to Java!");
count++;
}
13
animation
int count = 0;
while (count < 2)
{
System.out.println("Welcome to Java!");
count++;
}
14
animation
15
Example (Average.java)
16
Infinite Loops
17
Infinite Loops
int count = 1;
while (count <= 25)
{
System.out.println(count);
count = count - 1;
}
18
Nested Loops
• For each iteration of the outer loop, the inner loop iterates
completely
19
Nested Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
10 * 20 = 200 20