Looping is the kind of code that will repeat a code or a series of code a number of times.
While loop is one type of looping in JAVA. Here is the structure.
while ( condition_is_true ) {
//execute codes here while the condition above is true
//if the condition above becomes false, the loop stops and continues at the next line
}
//next series of codes to be executed after the loop condition becomes false.
Do while loop
is another type of looping in JAVA. It will execute the code once then a
condition will be check. If the condition is true, loop. Here is the
structure.
int counter = 0;
do {
System.out.println("Hi,");
counter++; //increment the counter variable
} while ( counter < 5 ); //if this condition is true, loop.
System.out.println("Hi,");
counter++; //increment the counter variable
} while ( counter < 5 ); //if this condition is true, loop.
For loop is also another type of looping in Java. Here is the structure.
for (variable_initialization;condition;increment/decrement) {
//execute codes here if the condition is true
}
Try to code this:
You will notice the difference of the do while loop from the two. After that, try to change the condition > (greater than) to < (less than) and try to run.
*Note:
do while loop will execute the code first then check the condition but
for loop and while loop will check the condition first before executing
the codes inside them.
Next: JAVA Arrays
No comments:
Post a Comment