Showing posts with label ROBOTICS TECH - 31. Show all posts
Showing posts with label ROBOTICS TECH - 31. Show all posts

Monday, 11 February 2013

For-loops


For-loops

For-loops are syntactically designed to be used with arrays. Though the behavior of a for-
loop may be duplicated by a while-loop, for readability, programmers typically use for-loops
when the intention of the loop is to manage an array.
 
for ( [ initialization ]; [ condition ]; [ increment ] ) {
// block of instruction
}
 
Listing 6.7: The syntax of a for-loop. The block of instruction is executed as long as the
condition is true.
When a for-loop is rst encountered, the [initialization] instruction is executed and
immediately thereafter the [condition] statement. If the [condition] statement is true,
the for-loop body block is executed. At the end of the block, program execution returns
to the [increment] statement and immediately thereafter the [condition] statement. If
the [condition] statement is true, the block is executed again and the program execution
returns to the [increment] statement. The [initialization] statement is only executed
once when the program execution rst encounters the for-loop. Thereafter, the [increment]
and [condition] statements are executed until the [condition] statement becomes false.
At rst, the for-loop operation seems overly complicated, but consider the code in Listing
6.8 which shows a typical application of for-loop syntax.


 
task main () {
int i;
int perfect_squares [10];
for (i =0;i <=9; i ++) {
perfect_squares [i] = i*i;
}
//
}
 
Listing 6.8: A simple for-loop that stores the rst 10 perfect squares in the array
perfect_squares.
In this case, the for-loop controls the value of the the array index, i, by initializing it to
0 and incrementing it by 1 through the values 0 through 9. In the loop body, we assign i*i
to the ith array element. After the loop is nished, the perfect_squares array contains
(0; 1; 4; 9; : : : ; 81).
Listing 6.9 shows a program that will scroll through a list of the lower-case letters of the
alphabet with a quarter-second delay between each letter.
 
task main () {
int i;
char alphabet [26];
for (i =0;i <=25; i ++) {
alphabet [i] = 'a' + i;
}
for (i =0;i <=25; i ++) {
nxtScrollText ("%c",alphabet [i ]);
wait10Msec (25);
}
}
 
Listing 6.9: Scrolls through the letters of the alphabet. The rst for-loop lls an array with
the letters of the alphabet. The second displays them to the screen with a quarter-second
delay between each new letter.
Notice the unusual addition of an integer and a character assigned to the alphabet array.
This is a useful method of manipulating characters via their positions in the alphabet. It
works via the notion of casting.