Main Content

Learning to Program - the conditional statement (if)

Archive - Originally posted on "The Horse's Mouth" - 2014-11-21 19:53:00 - Graham Ellis

Every language has some sort of conditional statement. That's a way of looking at some sort of setting or status in the program and performing some sort of action based on that setting or status.

such statements take the form ...
  if {some sort of condition is true} then {run a group of statements}

if

The word if applies in every language that we teach at Well House Consultants at present, but how we define the condition, how we signify the end of the condition and the start of the group of statements, and how we stop and start that group varies.

Some definitions
- a BLOCK of code is a series of statements grouped together. Actually zero or more statements, as at times you'll want to have a "do nothing" group
- DELIMITERS are the characters or character groupings thet start and end blocks. They may be the words then and , they may be the characters { and }, or thy may be a pattern of spaces and tabs that insets the block in the source code. Sometimes they may be left out, and if the language supports that they imply a block of a single statement.

The condition that's used in an if statement if going to be an expression that evaluates to a "yes" or "no" value - true or false. Exactly what comprises true and false varies between languages - very often if your conditional expression works out at zero, that's false and it it works out to any other number, that's true. But numbers are only used in this way a small proportion of the time, as languages come with special oeprators which compare two values and return true or false based on that comparison. Commonly they are:
  == ... "is equal to"
  != ... "is not equal to"
  < ... "is less than"
  <= ... "is less than or equal to"
  > ... "is greater than"
  >= ... "is greater than or equal to"

But BEWARE ... in some languages (SQL and Lua) even these vary, and in many languages (Perl, PHP, Shell for example) there are alternatives which do somewhat different things, and in some (Java, Python, Ruby, SQL, C, C++ for example) there are functions (I'lltell you about those another time) which you may call to make alternative comparisons. In other words, you're never limited to just the six comarisons.

These are notes to accompany your "Learning to program in xxxxx" course at Well House Consultants, so I'm not going to attempt to describe all the options here. Instead, your tutor will demonstrate the first, most basic conditional statements to you at this point and let you try them out.

One of the question that comes up for newcomers to programming is "why do I need a closing delimiter?". It's needed to tell your program that you've reached then end of code that's only run in certain circumstances and you're back into "always" code beyond that point. Imagine that you're driving a car and you decide to pull into a service station:
  if (ineed == "loo") then { ......}
The block of code in the curly braces defines what you need to do in the service station, but then when you get backon the main road it's "carry on as before", even if one or two of the variables (such as your comfort level) have been amended. The closure is vital as it removes the need for all subsequent code to be repeated - it's an indication of the coming together.

elseif and else

Usually, you'll want to perform one action if a condition is true, and some different action if the condition is false. Whilst it would be possible for you to write the "opposite" if statement, that's ineffiecent (at writing and run time) and prone to error, so languages support some sort of otherwise statement.

You can follow an if with one or more elseif or elsif or elif clauses (the keyword varies from language to language!) which in each case will have a further condition attached to them, and they'll have a block of code that runs if that alternative condition is true.

Note that the order of the various conditions is important, as once a true condition is found as the code runs, that's the block that will be run and the following ones won't be, even if the condition on them is also true.

Finally, you may finish your if statement with else and a block to accompany it. This is your 'catch all' or safety net which will be performed if neither the if condition, nor any of the el[se]if conditions was true. The else is optional, you can only have one of them, and there is no condition attached to it.

nested and joined conditions

You'll often find that you want to test for conditions within conditions (i.e. within the block of what to do) and you can do this. If you've stopped at the service area above because you needed a natural break, you'll be making other subsidiary decisions in there about wheth to use the loo, have a coffee, buy sweets for the kids, call your desination to update your arrival time, etc. Note that you'll complete all of those extra actions before you complete the main action of making a stop at the service area ... So nested conditional start in the order 1, 2, 3 but end 3, 2, 1.

There are also times that you want to perform a certain action only if two conditions are true. You could do this with nested blocks, but you'll also have an alternative, typically using the words and or or to link up conditions into a single composite conditions. Very often, either && or & are alternatives (with subtle differences) for and, and or may be relplaced by || or |. This is a subject for much deeper study later in the course.

testing

As soon as you start introducing condtional code, you introduce multiple routes through the code so it becomes very important to give throught to a thorough testing regime.

As a minimum, you should test your progran before its use in a live application by running every single possible condition though its true and false routes. And you should consider also:
* Running your code such that all combinations of conditions are tested
* Testing your data where both valid and invalid user inputs are made
* Remember to test "boundary" conditions ... if you're testing for age under 18, run your code with (say) 16 and 20 ... BUT ALSO with 18 itself.

Testing gets to be repetitive and (let's admit it) a bit boring at times, and it's far too easy for us to skip. Yet it really should be repeated in full for each and every iteration / release of the code. We'll broach the detail of testing later on the course, but for the moment bear in mind that a standard set of tests, automated in a file so that you can easily rerun them, and with extra software to pick up hundreds or thousands of passes and the occasional fail is going to be far better that your programmer working through each and every test at every upgrade. You might even want to write the tests before you write the code that it's going to be testing - that's Test Driven Development or TDD