Saturday, August 15, 2009

while loop

Loop is the mechanism to implement repetition (or iteration). There are different types of loops and while is on of them. while loop can be used to repeat certain statement. while loop has the form:

while( loop_condition )

If there is only one statement then the form can be:

while( loop_condition )

We can still use the braces even though there is only statement.

while repeats the statement(s) in its body as long as the loop_condition remains true. The loop terminates when the condition becomes false. The program continues its execution from the next statement following the while loop.

A while loop is a pretest loop, i.e. the loop condition is evaluated, before the body of the loop is executed. If the condition is false the first time it is evaluated the loop body is never executed. The loop condition can be any expression with legal values of true and false. Any expression with relational operators between its operands ( ==, !=, <, <=, >, >=, !, &&, || ), i.e. boolean expressions.

There is a basic data type bool that has two possible values: true and false. When evaluated, the before mentioned loop condition statements give a value of the type bool. A variable of the type bool can also be used as a loop condition. For historical reasons from the C language integers are also interpreted as boolean values: 0 equals false, all the other values equal true. In some situations other data types can also be used as a condition.

Previous post

Next post

No comments:

Post a Comment