W6-Presentation01-Repetition Control Structures
W6-Presentation01-Repetition Control Structures
The statements inside the while loop will be executed as long as the
loop_condition evaluates to true. If the loop_condition evaluates to false it will exit
or stop the loop.
For example:
int x = 1;
while(x <= 5){
System.out.print(x);
x++;
}
Below is the flowchart for the code snippet above:
The following are other examples of while loops,
Example 1:
int x = 5;
while (x>0)
{
System.out.print (x);
x--;
}
The example above will display 54321. In this case we used decrement
operator. The while loop will stop when the value of x becomes 0.
Example 2:
int x = 0;
while(x<=5){
System.out.println(“Hello World!”);
}
The sample code above will have an infinite loop or it will just display “Hello
World” continuously without stopping. It leads to infinite loop because we didn't put
statement that controls the iteration. In this case, the value of x remains 0 and
loop_condition (x<=5) is will always be true.
Example 3:
//no loops
int x = 5;
while(x<5){
System.out.println(“Hello World!”);
}
The sample code above will display nothing because it will not reach the
statements System.out.println(“Hello World!”); due to loop_condition (x<5)
evaluates to false.
While Loop Sample Program: