if
In the previous summary, we discussed what a conditional is and how it is constructed. An if construct is the fundamental decision-making feature of all programming languages. With it we declare a condition – a fork in the road, a decision point for our programs.
In real life when we ask a question we expect an answer. For example if you ask someone “Did you go to school?†You expect a yes/no result. Similarly if is the most common way of asking questions when it comes to programming.
As discussed earlier, the conditional expression evaluates to a boolean value (true or false,) which in turn controls the flow of the program:
If it evaluates totrue, control enters the if-block.
If it evaluates to false, the if-block is by-passed.
Looks complex, doesn't it? Nope! Here's the same thing in pseudo-code:
if the cat starts coughing – do a bunch of things: push him off the bed, yell for your girlfriend to come take care of him, and run like hell.
If he's not coughing, skip all of that and carry on coding in Flash!
Also, no alternatives to the “entry/bypass mechanism†are considered -- no options such as “what to do otherwiseâ€, because there is no “otherwiseâ€. This construct can be used only for simple condition testing, without any other alternative provided. (He's either coughing or he's not – there's no in between.)
Example
Consider, for example, everyone’s favorite Last Action Hero being interviewed about his choice of reincarnation based on questions posed by his “die-hard†fans:
Q. “If you were to be born again as a musician, who would it be?â€
Q. “If you were to be born as an animal, what would it be?â€
Pseudo-code that mimics the above scenario in the Hero’s mind, would look like:
var reincarnation:string = “…â€;
//some statements here
if(reincarnation == “musicianâ€)
trace(“I’ll Be Bachâ€);
if( reincarnation == “animalâ€)
trace(“Next time, Duckâ€);
Note
Notice here that this piece of code needs to be put in ourmain() function to be called for execution. There can be as many stand-alone “if†statements as the programmer wants to put in the code. This can be verified by the reader by writing a simple main() function with the above code embedded. This simple condition testing lays the foundation for decision making in computer programs.