/* */

Tuesday, 21 August 2012

looping


While loop

While loop uses the while keyword, followed by a condition. The condition is tested; if it's
outcome is true it will carry out the body below it once. Then it will test the condition
again, if it's still true, carry out the body etc until the condition is false.

syntax:

while (condition) {
statement
}

The statement bit is called the while body. Put simply, a while loop is saying "while the
condition is true, do whatever's insode the {}".

loop invariants

Often a good idea is to write the objectives of the loop in a comment that you can use to
understand and determine whether the loop should continue or stop. The comment should
concisely outline the objective of the loop, and indicate when it has done its job.

if loop

An if statement can take two forms:

if (condition)
statement

or...

if (condition)
statement1
else
statement2

The if statement works similarly to the while statement, it tests the condition, if its
true, it will carry out the statement beneath it. If it's false, it'll either jump out
of the if statement (first example), or carry out the else statement (second example).

for loop

the for loop is a shorthand way of expressing a while loop:

for (int r =0; r != rows; ++r) {
//do the stuff
}

This for loop will cause r to take on a number of values. The first is 0, the last will
be rows -1.
We think of 0 as being the beginning of the range and rows as being off-the-end value

No comments:

Post a Comment