music |
OSdata.com |
iterative (do or for) loop
summary
This subchapter looks at the iterative loop (do or for loop).
free computer programming text book projecttable of contents
|
music |
OSdata.com |
This subchapter looks at the iterative loop (do or for loop).
free computer programming text book projecttable of contents
|
This subchapter is a stub section. It will be filled in with instructional material later. For now it serves the purpose of a place holder for the order of instruction.
Professors are invited to give feedback on both the proposed contents and the propsed order of this text book. Send commentary to Milo, PO Box 1361, Tustin, California, 92781, USA.
The most basic loop or repetition structure is known as the DO LOOP. This is also called the FOR LOOP. Another name for this is the Iterative DO or Iterative loop.
In the DO LOOP, you instruct the computer exactly how many times you want it to repeat a particular task and it does it exactly that many times (assuming no crashes or bugs).
Please remember that the examples in this informal discussion are not from any actual programming language. These are designed to illustrate the basic principles.
Using our average example from above, you will notice that after the first (initialization) steps (1.a and 1.b.) and before the last (final computation) step (7), that each of the pairs of steps are exactly the same. Instead of writing out each and every step, we could describe the two basic steps and put them into a DO LOOP:
Initialize;
BEGIN
Subtotal := 0;
END;
DO five times;
BEGIN
Add the next number to the Subtotal;
END;
Finish;
BEGIN
Answer is Subtotal divided by 5;
END;
In most programming languages there is some variation of a loop count variable. The number of times to loop is established by setting the initial value of the loop count variable and setting the limit for the the number of times to repeat the DO LOOP.
Initialize;
BEGIN
Subtotal := 0;
IF there are no numbers available to average
THEN REPORT an ERROR and STOP;
END;
DO Count := 1 TO 5;
BEGIN
Add the next number to the Subtotal;
END;
Finish;
BEGIN
Answer is Subtotal divided by Count;
END;
You may notice that we started the count at one rather than zero. We did this to have the DO LOOP perform exactly five repetitions with the count of numbers matching the standard counting numbers.
You may also notice that we used the Count outside of the actual DO LOOP. Note that in many prgramming languages you can not actually use the loop count variable outside the loop (although you can usuually use it inside the DO LOOP). A common work-around is to create an extra copy of the count variable that we can use outside the DO LOOP:
Initialize;
BEGIN
Subtotal := 0;
NumberCount := 0;
IF there are no numbers available to average
THEN REPORT an ERROR and STOP;
END;
DO LoopCount := 1 TO 5;
BEGIN
Add the next number to the Subtotal;
Increment (add one to) the NumberCount;
END;
Finish;
BEGIN
Answer is the Subtotal divided by the NumberCount;
END;
The loop count variable is considered to have a start value and a finish value. The loop count variable is often called the control variable. The starting value for the control variable is often called the initial value. The finishing value for the control variable is often called the limit value.
Ah, variable names.ÊLength is not a virtue in a name; clarity of expression is.ÊA global variable rarely used may deserve a long name, maxphysaddr say.ÊAn array index used on every line of a loop neednt be named any more elaborately than i.Ê Saying index or elementnumber is more to type (or calls upon your text editor) and obscures the details of the computation.ÊWhen the variable names are huge, its harder to see whats going on.ÊThis is partly a typographic issue; consider
for(i=0 to 100)
array[i]=0 ;
vs.
for(elementnumber=0 to 100)
array[elementnumber]=0;
The problem gets worse fast with real examples.ÊIndices are just notation, so treat them as such. Rob Pike, Notes on Programming in C, February 21, 1989
Some programming languages will allow greater flexibility in how the loop count variable is used. Many programming languages give the choice of counting up or counting down. Computers are really good at counting down to zero. This shouldnt matter much with modern computers (where the ability to easily read and understand someone elses program is far more important than a nanosecond saved somewhere), but you will certainly encounter this when working on old programs from back in the days when this time difference was important.
Most prgramming languages allow the initial value and limit value to be variables. This allows the flexibility of the program deciding these values while it is running rather thaan the programmer having to know the values in advance when the program is written. This is known as the difference between run time and compile time.
Some programming languuages allow the step to be something other than a step up or down by one (increment and decrement). An example might be a loop that only works on odd or even numbers (the initial value might be one (1) for odd numbers and either zero (0) or two (2) for even numbers).
In the following example, the loop would be performed a total of 10 times and each time through the loop the count would be a multiple of ten (for some reason we need multiples of ten in the work we are doing).
DO COUNT := 10 to 100 STEP UP BY 10;
If the programming language allows for steps other than increment, the size of the step is known as the step value or the modification value. There is also the possibility that the step value can be a variable and determined at run time.
Some programming languages allow a lot more variations, such as counting from 1 to 99 by steps of 1 and then coutning from 100 to 1,000 by steps of 100., or even more complicated versions. Because this is an informal discussion, I wont get into those complexities here, but I wanted you to know that they can exist.
Stanford CS Education Library This [the following section until marked as end of Stanford University items] is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Copyright 1996-2003, Nick Parlante, nick.parlante@cs.stanford.edu.
The for loop in C is the most general looping construct. The loop header contains three parts: an initialization, a continuation condition, and an action.
for (<initialization>; <continuation>; <action>) {
<statement>
}
The initialization is executed once before the body of the loop is entered. The loop continues to run as long as the continuation condition remains true (like a while). After every execution of the loop, the action is executed. The following example executes 10 times by counting 0..9. Many loops look very much like the following
for (i = 0; i < 10; i++) {
<statement>
}
C programs often have series of the form 0..(some_number-1). Its idiomatic in C for the above type loop to start at 0 and use < in the test so the series runs up to but not equal to the upper bound. In other languages you might start at 1 and use <= in the test.
Each of the three parts of the for loop can be made up of multiple expressions separated by commas. Expressions separated by commas are executed in order, left to right, and represent the value of the last expression. (See the string-reverse example below for a demonstration of a complex for loop.)
Stanford CS Education Library This [the above section] is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Copyright 1996-2003, Nick Parlante, nick.parlante@cs.stanford.edu.
This [the following section until marked as end of Stanford University items] is document #108 [Essential Perl] in the Stanford CS Education Library --see http://cslibrary.stanford.edu/108/. This document is free to be used, reproduced, or sold so long as this paragraph and the copyright are clearly. Copyright 2000-2002, Nick Parlante, nick.parlante@cs.stanford.edu.
Perls control syntax looks like Cs control syntax. Blocks of statements are surrounded by curly braces { }. Statements are terminated with semicolons (;). The parenthesis and curly braces are required in if/while/for forms. There is not a distinct boolean type, and there are no true or false keywords in the language. Instead, the empty string, the empty array, the number 0 and undef all evaluate to false, and everything else is true. The logical operators &&, ||, ! work as in C. There are also keyword equivalents (and, or, not) which are almost the same, but have lower precedence.
These work just as in C
for (init_expr ; test_expr ; increment_expr ) {
stmt;
stmt;
}
## typical for loop to count 0..99
for ($i=0; $i<100; $i++) {
stmt;
stmt;
}
The next operator forces the loop to the next iteration. The last operator breaks out of the loop like break in C. This is one case where Perl (last) does not use the same keyword name as C (break).
This [the above section] is document #108 [Essential Perl] in the Stanford CS Education Library --see http://cslibrary.stanford.edu/108/. This document is free to be used, reproduced, or sold so long as this paragraph and the copyright are clearly. Copyright 2000-2002, Nick Parlante, nick.parlante@cs.stanford.edu.
26 The loop statement provides the basic iterative mechanism in the language. A loop statement specifies that a sequence of statements is to be executed repeatedly as directed by an iteration scheme, or until an exit statement is encountered. :Ada-Europes Ada Reference Manual: Introduction: Language Summary See legal information
Coding example: I am making heavily documented and explained open source code for a method to play music for free almost any song, no subscription fees, no download costs, no advertisements, all completely legal. This is done by building a front-end to YouTube (which checks the copyright permissions for you).
View music player in action: www.musicinpublic.com/.
Create your own copy from the original source code/ (presented for learning programming).
return to table of contents
free downloadable college text book
Because I no longer have the computer and software to make PDFs, the book is available as an HTML file, which you can convert into a PDF.
previous page | next page |
Tweets by @osdata |
free computer programming text book projectBuilding a free downloadable text book on computer programming for university, college, community college, and high school classes in computer programming. If you like the idea of this project, Supporting the entire project: If you have a business or organization that can support the entire cost of this project, please contact Pr Ntr Kmt (my church) free downloadable college text book on computer programming. |
This web site handcrafted on Macintosh computers using Tom Benders Tex-Edit Plus and served using FreeBSD .
UNIX used as a generic term unless specifically used as a trademark (such as in the phrase UNIX certified). UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company Ltd.
Names and logos of various OSs are trademarks of their respective owners.
Copyright © 2010, 2011 Milo
Created: October 31, 2010
Last Updated: March 4, 2011
return to table of contents
free downloadable college text book
previous page | next page |