Loops
Loops
Loops
If (conditional_expression)
{
statements_to_execute
}
//Example 2
If (conditional_expression)
{
statements_to_execute
}
else
{
statements_to_execute
}
//Example 1
if(a == b)
{
c++;
}
//Example 2
if((x <= y) && (y <= z))
{ System.out.println("Of course:\n"); System.out.println("x
is less than or equal to z");}
//Example 2
if(a == b)
{
c++;
}
else
{
c--;
}
Example
if( color==green) {
System.out.println(“color is green”);
}
else if(color==yellow) {
System.out.println(“color is yellow”);
}
else {
System.out.println(“color unknown”);
}
//do while loop
do{
Statements_to_execute
}while(conditional_expression);
// while loop
while(conditional_expression)
{
statements_to_execute
}
//for loop
for(int i = 0; conditional_expression; i++)
{
statements_to_execute
}
A switch works with the byte, short, char,
and int primitive data types
Each case value must be a unique literal
Class breakloop{
public static void main(String args[]) {
for(int i=0; i<10; i++) {
if(i==5) break; //terminate loop when i=5
System.out.println(“i:” +i);
}
System.out.println(“Loop Completed”);
}
}
i: 0
i: 1
i: 2
i: 3
i: 4
Loop Completed
Sometimes we do not need to execute
some statements under the loop, then we
use the continue statement that stops the
normal flow of the control and control
returns to the loop without executing the
statements written after the continue
statement.
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print( i + " ");
if(i%2==0) continue;
System.out.println(" ");
}
}
}
Output:
01
23
45
67
89