Lab6-Loop
Loops Have:
- Some kind of initialization
- A body
- And a loop terminating condition
Otherwise, a non terminating loop is known as infinite loop and you will think your machine is broken.
While:
while(condition) {
...statements for execution;
}
- The condition of while loop has to be a boolean expresion
-
- If true: the statements in the body of the loop will continue to execute.
- Until the condition becomes false
- If false: while loop terminates. This is caused by something in the body of the loop.
In while loop you can't determine how many times the loop would run.
Do:
do {
...statements;
} while (condition);
- Do loop starts out with statements instead of condition:
Thus, the body of the do loop executes before the condition.
- So, initially the body of do loop is executed
- Then the condition of a while loop is evaluated
- And when the condition becomes false the loop stops otherwise body of do loop will keep executing.
In do loop, the execution takes place at least once.
For:
for(initialization; condition; iteration){
...body (statements) of the loop;
}
- Unlike do loop, the condition for
for loopis tested before execution: -
- First you initialize the vairable
- Then you set the condition according to which the loop will execute
- And finally the iteration is set: How many times you want the loop to execute?
In for loop, you can set the number of times you want the body to be executed.