Main Content

Breaking the running sequence - an introduction to conditional statements and loops

Archive - Originally posted on "The Horse's Mouth" - 2011-04-11 07:06:27 - Graham Ellis

A program is a series of instructions which are run in sequestially - or so you'll be told when you start programming. And, indeed, that's the default - the way it is unless you write code to do something different. "A program is a series of statemnets each separated by [something] which run one after another".

But ... there are going to be times that you only want someting to be done in certain conditions. Do you say to a guest in your low-ceilinged cottage "mind your head"? You only want to do so if your guests is fairly tall (in fact, on last week's C and C++ course we decided that you do NOT need to tell very tall guests as they'll be used to ducking everywhere in their daily life!), but you don't want to insult people who are really short. So - in our code - we put a conditional statment of the form:
  if (condtion) {things to do only if true}

The example we wrote - full source code, a longer decsription that's specific to C++ and C, and sample output may be found [here].


There are time, too, where you want to keep repeating statements - "do that again" - and typically a whole series of statements, until a certain condition is met. For example, if you've eaten rather well in the run up to Christmas, and perhaps over Christmas as well, you may with to loose 2kg and see if you're healthier. Well - yes, you're healthier, but you could do with loosing anothe couple of kgs, and another couple, and so on until you reach an ideal body mass index ... and in coding terms, that's a loop. We write it of the form:
  while (condtion) {things to do only if true}
which (you'll note) is almost identical to my if statement. The difference is that when cose like this is run, the program goes back and tests the condition again once it's completed the running of the block the first time ... and it keeps doing so while the condition remains true.

The example we wrote - full source code, a longer decsription that's specific to C++ and C, and sample output may be found [here].

---OOO---


If you find your self repeating the same thing a number of times one after another in your code, you've probably got it wrong - you should be using a loop. As well as while loops, C and C++ support for loops which offer a start point - step - end point capability so that you can say "go from 1 to 12 in steps or 1" all in a single statement (and they can do much more too). In other languages, you'll find other loop statements such as loop, foreach and until.