Loops

While-do statements

The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:

while (expression) {
     statement(s)
}

The while statement evaluates an expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

Example: This while-do loop counts from 1 to 10:

int count = 1;
while (count < 11) {
     System.out.println("Count is: " + count);
     count++;
}

Do-while statements

The Java programming language also provides a do-while statement, which can be expressed as follows:

do {
     statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.

Example: This do-while loop counts from 1 to 10:

int count = 1;
do {
     System.out.println("Count is: " + count);
     count++;
} while (count < 11);

For statements

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

for (initialization; termination;
     increment) {
    statement(s)
}

When using this version of the for statement, keep in mind that:

  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

Example: This for loop counts from 1 to 10:

for(int i=1; i<11; i++){
     System.out.println("Count is: " + i);
}

Source:

results matching ""

    No results matching ""