DECISIONS AND LOOPS

Imagine: you are driving a car in the road... Now: you have two directions to go. You need to make a decision: right or left?

A computer program is a serie of lines of code. The computer goes line after line, like a car in the road. But it's possible to built a program that has, at some moment, two paths. The computer will need to make the decision. Normally we write an if-else block inside the program to define a conditional decision:

The if-else block is something like:

if (test expression){

 statements to be executed when the test result is "true"

}
else{

 statements to be executed when the test result is "false"

}

We will see soon an example.

In programming science a loop is a repetitive execution of some lines of code when only a value (a counter) changes each time one roundtrip is completed.

We have the loop block whose sintax is a little crazy:

for(initializer;test;update){

 statements

}

The loop block puts three expressions inside the parentheses, separeted by semicolons. The first expression, usually called the initializer is where you set up the loop, giving values to any variable that are tested. The initializer expression in a loop block is only executed once, and it is always executed, regardless of whether the test condition is true or false.

The test condition is a boolean expression. The expression is evaluated each time and, if found true, the statements in the body of the block are executed. However, before the test condition evaluation, is executed the update expression.

Lets go to see a sample group of lines of code:


for(i=0;i<5;i++){
 x = 1*2;
 Chat.print("The double of the counter is: ',x);
}

In the initial roundtrip the i value is 0, its double is the same 0.

REMEMBER: We have seen that :

      i++    is the same than:  i = i + 1

In the second roundtrip: the i value is 1, its double is 2.

In the next roundtrip: the i value is 2, its double is 4.

In the next roundtrip: the i value is 3, its double is 6.

In the next roundtrip: the i value is 4, its double is 8.

In the next roundtrip: the i value is 5, and the loop stops because: i value is NOT less than 5 (the test condition).

The output of these lines of code will be:

The double of the counter is: 0
The double of the counter is: 2
The double of the counter is: 4
The double of the counter is: 6
The double of the counter is: 8



PREVIOUS LESSON NEXT LESSON
T.CONTENTS HOMEPAGE