Conditional Statements and Loops in Programming
Created | Updated Feb 2, 2007
Conditional statements and loops are really quite an important aspect of many programming languages; without them, blocks of code would have to be copied and pasted many times over, and programs would be unable to react to any changes whatsoever. Along with commands such as 'continue' and 'return', conditional statements and loops allow the programmer to control the flow of a program, making it possible for small sections of code to perform quite powerful operations. This Entry looks at some common statements found in many third and fourth generation programming languages1. Despite sharing the same structures the languages are all slightly different, and so this Entry will present examples in a meaningless yet easily-understood generic language. Some languages may differ through having brackets in various places, while others may lack the 'end' statements used in these examples, and some may have loops that take up just a single line of code and look very nasty indeed.
Conditional Statements
A conditional statement is one which makes the computer compare two or more variables in some way and decide that the outcome is either 'true' or 'false', and then feeds this into a function such as 'if' or 'while'. The next piece of code after the conditional statement is then run only 'if ... is true' or 'while ... is true', with the latter repeating the comparison and running the code again until the condition becomes false. An example written in generic code would be:
if number == 42
print("Life, the Universe and Everything")
end
The '==' means 'is equal to', and is just one of many relative operators, these being the things used to compare one variable to another. Thus, the code asks if 'number' is equal to 42 and will only run the next line if this is the case. If 'number' does contain the value 42, the phrase 'Life, the Universe and Everything' will be displayed on the screen by the 'print' command. If 'number' contains anything else, then execution of the program will skip to the next line after 'end', if there is one, and will thus not display the message.
Some Common Relative Operators
- == means 'is equal to'.
- ~= or !=2 means 'is not equal to'.
- < means 'is less than'.
- > means 'is greater than'.
- <= means 'is less than or equal to'.
- >= means 'is greater than or equal to'.
Logical Connectors
You may have noticed that conditional statements using just the relative operators can only compare two things3, no more and no less. This can be improved with the use of logical connectors, which are basically Boolean operators such as AND, OR and NOT. For instance:
if temp < 25 AND temp > 15
print("Temperature is within acceptable limits.")
end
The 'AND' represents the Boolean operator AND, and so the second line of code will only be executed if 'temp' is less than 25 and greater than 15. In some languages, AND may be represented by '&&'. Other common symbols for logical connectors are '||', which represents OR, and either '!' or '~', which represent NOT in different languages. Note that the latter only requires one input, as it basically changes an output of 'true' into a 'false' and vice versa. Note that if the first comparison made is enough to decide whether the whole statement is true or false4, the computer may, depending on the particular language, choose to ignore the other comparisons and just get on with it.
The 'if' Statement
The example above contains a very simple use of the 'if' statement, which executes a section of code only if the conditional statement is true. However, other statements can also be incorporated into the block of code to save time. An 'else' statement added to a block will run only if the original conditional statement was false, and an 'elseif'5 does the same only if a further statement is true. For instance:
if temp < 25 AND temp > 15
print("Temperature is within acceptable limits.")
elseif temp >= 25
print("It's too hot!")
elseif temp <= 15
print("It's too cold!")
else
print("Error - input is not a valid number.")
end
If the temperature isn't within the correct limits, the computer will look to see if any of the 'elseif' statements are true. Failing that, it will execute the code following the 'else' statement, which in this case is an error message as the program should cover all possible numerical inputs.
The 'switch' and 'case' Statements
An alternative to the 'if' statement, 'switch' can be used to look at a specific variable and then execute a different piece of code for each probable value of it using a series of 'case' statements. The 'switch' statement followed by the variable of interest come first, followed by a list of cases:
switch day
case 0
print("Sunday")
case 1
print("Monday")
case 2
print("Tuesday")
case 3
print("Wednesday")
case 4
print("Thursday")
case 5
print("Friday")
case 6
print("Saturday")
otherwise
print("Error")
end
Upon encountering a 'switch' statement the computer will look for a 'case' statement with the correct value, running the code after 'otherwise'6 if none of the cases match the value stored in the variable. The code above will display the name of a day depending on which integer between 0 and 6 is stored in 'day', with any other input resulting in an error message. Note that in some languages, failing to add a statement after 'case ...' forces the computer to execute the statement corresponding to the next case instead - this is known as 'falling through'. In these languages, a 'break' statement (see below) or similar is required to prevent execution of every case that follows.
Loops
Unlike the 'if' and 'switch' statements, loops have the ability to force the computer to run the same block of code several times, thus allowing several iterations of the same calculation or the processing of several values using the same section of code. The simplest way to form a loop is using the age-old GOTO statement, which transfers control to a given line of a program. A simple example of the GOTO function in conjunction with 'if' would be:
10 n = 1
20 n = n + 1
30 if n < 5 goto 20
40 if n > 5 goto 60
50 return
60 print("Error")
The above program will continually add one to the value stored in 'n', with execution jumping back to line 20 unless n becomes equal to five. If, through some error, n became greater than five, execution would jump to line 60. Note the dependency of the GOTO statement on the line numbering system used. While '==' and '~=' are relative operators, the '='7 in the third line simply tells the computer to calculate the value of the expression on the right hand side and to store the result in the variable on the left.
A command similar to the GOTO statement even exists in machine code. In X86 machine language, the JMP instruction allows program execution to jump to an explicit address (similar to the line number in BASIC), while other instructions such as JNE (Jump if Not Equal) will jump to an address only if certain conditions apply. However, most modern programming takes place in third and fourth generation languages, where there are three common choices - 'while', 'do while' and 'for'.
The 'while' Loop
The 'while' statement simply repeats a loop while the statement at the start of it is true, with the loop being executed continually until the statement becomes false. For instance:
number = 1
while number ~= 42
number = number + 1
end
This code will repeatedly add one to the value stored in 'number' until it becomes equal to 42, after which the computer will skip to the line after 'end'.
The 'do while' Loop
Appearing in some languages as an alternative to 'while', the 'do' statement causes the computer to run a loop once and then see if it should run it again, making it useful when a check has to come after an operation has been performed. An example would be:
do
print("Display footie scores - yes (y) or no (n)?")
scanf("%n", &answer)
while answer ~= 'y' AND answer ~= 'n'
This code asks for an input and then checks to see if the input matches what the code was expecting, and run the loop again if a valid input was not provided. The '%n' tells the computer to receive a string input such as 'y' or 'n' via the 'scanf' command, which is then put into the variable 'answer' to be compared with the expected inputs. Note that some languages do not support this loop and may either produce an error due to the 'do' or misunderstand which section of code the 'while' statement refers to. In Pascal, the 'do while' loop is known as the 'repeat until' loop.
The 'for' loop
Probably the most powerful of all the loops, the 'for' loop comes in various forms depending on the programming language in question. In some cases it will simply run the loop a certain number of times, using a syntax such as 'for x = 1:100 [contents of loop] end' which would run the same code a hundred times, with the colon indicating that the computer should give 'x' each integer value between 1 and 100. Meanwhile, other languages allow require a logical comparison, with the statement including the variable of interest, the comparison and the operation to perform on the variable:
y = 0
for n = 1; n <= 4; n++
y = y + n
end
The variable 'n' starts off being equal to one, and is then increased by one each time the loop runs - the command 'n++' simply increments the value of n by one. Once n <= 4 becomes false, execution skips to the next line after 'end'. The code therefore adds the current value of 'n' to 'y' during each execution of the loop, with y reaching ten, the fourth triangular number8, after the last implementation of the loop.
Other Commands
Other commands exist to allow programmers to leave a loop or skip to the next cycle of a loop while halfway through the block of code. The 'break' statement causes the code to skip to the first bit of code after a 'for', 'while' or 'switch' block, while the 'continue' statement causes execution to jump to the next cycle of a 'for' or 'while' loop if there is one. Both are usually used with an 'if' statement:
number = 43
while number != 42
number = number + 1
if number > 42
break
end
end
As we will never reach 42 by repeatedly adding one to 43, the break function acts to prevent the loop from cycling indefinitely. Finally, a mention should be made of the 'return' statement, which ends execution of the function or program it appears in, and thus can also be used to interrupt loops.