music |
OSdata.com |
if-then
summary
This subchapter looks at if-then.
free computer programming text book projecttable of contents
|
music |
OSdata.com |
This subchapter looks at if-then.
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 IF-THEN structure is pretty straght forward. Your program tests to see if something is true. If the test is true, then your program does something (usually a sequence, although it can be any combination of the three control structures).
For example, if you are tall enough, then you may go on the amusement park ride (which also implies that if you are not tall enough, then you cant)..
The thing being tested in an IF is called the condition.
The two most common tests are for the condition to be TRUE or for the condition to be FALSE. Sometimes it is easier to write a program with a negative test (testing for a FALSE condition) rather than a positive test (testing for a TRUE condition). Sometimes it makes the program easier to read and understand (and therefore easier and less expensive to maintain over years or decades) for the test to be for a FALSE condition.
While the basic control structure is testing for TRUE or FALSE, the test condition often can be for things slightly more complex conceptually, such as equality (are two thing sexactly equal), inequality (greater than or less than), length, time, emptiness, fullness, completion, incompletion, etc.
Note also that we can have a simple test (only one condition is tested) or a compound test (multiple conditions are tested). Compound tests have potential problems in different programming languages, which will be discussed in detail when we get to the appropriate section.
The THEN part is what is done if the condition passes (Id say if the condition is true but you might have been testing for the condition to be false). The THEN part can be a single sequential step, a block (or group) of sequential steps, a block or group of any combination ot the three control structures, or a function or subroutine.
After the test is completed and the action possibly taken, the program continues on to the next item in the sequence of steps. This is an important feature of structured programming: exactly one entry and exactly one exit. It is a disaster for maintenance if the program can start wandering all over the place.
Using our average example, we might be interested in testing for zero divide before performing a division. Both elementary algebra and computer hardware reject any attempt to divide by zero (and the computer hardware can reject your attempt by freezing or otherwise crashing).
In our sequence example for finding an average, we never actually stated where the numbers to be averaged came from. They just were there when we needed them. What would happen if we never received the input numbers? When we attempted to do the division of the subtotal by the count, the count could have still been zero. The program crashes.
We could place a test for the count being zero just before we attempt to divide:
IF count NOT EQUAL zero (0)
THEN average = subtotal / count;
This avoids the program crashing.
We could also place a test for the existence of the numbers, somewhere near the start of the sequence (as one of the initialization steps). We would then place the entire rest of the block of sequential steps into the THEN portion, skipping the entire process if we dont actually have our five input numbers. This approach would not only avoid a divide by zero crash, but also avoid wasting a bunch of computation time on something that is going to fail anyway.
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.
Both an if and an if-else are available in C. The <expression> can be any valid expression. The parentheses around the expression are required, even if it is just a single variable.
if (<expression>) <statement> // simple form with no {}'s or else clause
if () { // simple form with {}'s to group statements
<statement>
<statement>
}
if () { // full then/else form
<statement>
}
else {
<statement>
}
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.
if (expr) { ## basic if -- ( ) and { } required
stmt;
stmt;
}
if (expr) { ## if + elsif + else
stmt;
stmt;
}
elsif (expr) { ## note the strange spelling of "elsif"
stmt;
stmt;
}
else {
stmt;
stmt;
}
unless (expr) { ## if variant which negates the boolean test
stmt;
stmt;
}
As an alternative to the classic if() { } structure, you may use if, while, and unless as modifiers that come after the single statement they control
$x = 3 if $x > 3; ## equivalent to: if ($x > 3) { $x = 3; }
$x = 3 unless $x <= 3;
For these constructs, the parentheses are not required around the boolean expression. This may be another case where Perl is using a structure from human languages. I never use this syntax because I just cannot get used to seeing the condition after the statement it modifies. If you were defusing a bomb, would you like instructions like this: Locate the red wire coming out of the control block and cut it. Unless its a weekday -- in that case cut the black wire.
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.
25 Case statements and if statements allow the selection of an enclosed sequence of statements based on the value of an expression or on the value of a condition. :Ada-Europes Ada Reference Manual: Introduction: Language Summary See legal information
The PHP if
statement is the keyword if
followed by the condition to be tested inside parenthesis. This is immediately followed by a single statement or a block of statements within curly braces {}
. The statement of block of statements is run if the condition evaluates to true and skipped if the condition evaluates to false.
In the following example, the variable $lastsong
is set to numeric zero if there are no GET
items in the URL and is set to the lastsong item if it exists.
if(empty($_GET))
$lastsong = 0;
else
$lastsong = $_GET["lastsong"];
This example comes from the simple music player of the music player programming example. Build your own free music player (no ads, no fees, no cost, all legal,, play almost any song).
The basic structure of a Ruby if statement is: the reserved word if, followed by the condition to be tested, optionally followed by either then or : (unless the entire statement is on a single line), folowed by one or more statements, and ending with the reserved word end.
All three of the following examples have the same effect:
if x == y then puts "successful test" end
if x == y
puts "successful test"
end
In Ruby it is also possible to use an if as a statement modifier. The following example has the same effect as the previous three examples:
puts "successful test" if x == y
The following material is from the unclassified Computer Programming Manual for the JOVIAL (J73) Language, RADC-TR-81-143, Final Technical Report of June 1981.
1.1.6 Flow of Control
For structured flow of control, JOVIAL has an if-statement, a
case-statement, and a loop-statement with an optional exit-
statement. Examples of these statements follow.
Here is an example of an if-statement:
IF SPEED < LIMIT;
FLAG = TRUE;
ELSE
BEGIN
FLAG = FALSE;
VIOLATION = VIOLATION+1;
End
If SPEED is less than LIMIT, this statement sets FLAG to TRUE and
does nothing else. If SPEED is not less than LIMIT, the
statement sets FLAG to FALSE and increments VIOLATION. The last
four lines of the example are a compound statement; the BEGIN-END
pair groups the assignments to FLAG and VIOLATION into a single
compound statement controlled by the ELSE clause.
The ELSE clause of an if-statement is optional; when it is
omitted, no action is taken when the condition is false.
Furthermore, if-statements can be nested, so complicated control
structures can be built up. When if-statements get large and
complicated, however, you can sometimes use a case-statement to
clear thigns up.
Chapter 1 Introduction, page 10
Commentary: This example interestingly highlights the problem of writing about software without testing it. The author missed the fact that travelling exactly at the speed limit is actually permissible. The test should have been for less than or equal to rather than just less than. This is why you always test the software you write, including test cases at each limit.
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, 2012 Milo
Created: October 31, 2010
Last Updated: October 14, 2012
return to table of contents
free downloadable college text book
previous page | next page |