While and do while

description of image


While Loop :


The syntax of the while loop is:

while (testCondition) {

// the loop body

}

Here’s how this loop works:

1. The while loop checks the test condition inside parentheses.

2. If the test condition is true, the loop body is executed

3. And the test condition is checked again.

4. This process goes on until the test condition evaluates to false.

5. When the test condition is false, the loop terminates.



Example: while Loop


● This program prints a sentence 3 times.



Do…while Loop


The do….while loop is similar to the while loop with one important difference. The body of the do…while loop is executed once before the test condition Is evaluated.

Its syntax Is:

Do {

// body of the loop

}

While (testCondition);

Working of do…while Loop

The body of do…while loop is executed once. Only then the test condition is evaluated.
If the test condition evaluates to true, the body of the loop is executed. Again, the test condition is checked.

This process goes on until the test condition evaluates to false.

When the test condition evaluates to false, the loop terminates.



Example 2: do…while Loop


● This program prints the number from 1 to 4.



Quiz


Question Text