An Introduction to Programming: Conditional Statements
Created | Updated Jan 28, 2002
I highly recommend reading the Variables entry in this project before reading this one, especially the bits about Boolean Variable and Boolean Operators.
What is a Conditional Statement?
A Conditional Statement basically compares two values and continues execution of the program according to the result of this comparision.
For example:
If(Money<Price)
{
Print 'Sorry, not enough money.';
}
This code will make the computer compare the values of the variables Money and Price, and if the value of Money is smaller than the value of Price, i.e., the condition is true, it will print the quoted line on the screen.
Conditional Statements can also be used in Loops.
Else Statements
In high level programming languages, there is an option to tell the computer what to do if the condition fails to be true. In the example above, if the value of Money is bigger than the value of Price or equal to it, the computer will simply have no instruction to execute. But if we add an Else Statement, we can tell the computer what to do in such a case:
If(Money<Price)
{
Print 'Sorry, not enough money.';
}
Else
{
Print 'OK, you have enough money';
}
So now, if the value of Money isn't smaller than the value of Price the computer will print the second quoted line on the screen.
Else If
There is also an option to check the validity of another condition, in case the previous one faild to be true. Many high level languages include an instruction called ElseIf, which enables us simply to say "If so then do this, otherwise if such then do that". I think this code can explain this best:
If(Money<Price)
{
Print 'Sorry, not enough money.';
}
ElseIf(GasTank<40)
{
Print 'The gas tank is too small.';
}
The computer will compare the values of Money and Price, and if the value of Money isn't smaller than the value of Price, it will go on to checking if the value of GasTank is smaller than 40. If it is, the second quoted line will be printed on the screen.
Multiple Conditions
Now, what if I want to do something only if several conditions are true, or if some of sevral are true? Well, you can do it the long way, and only check each condition if the previous one was true, as seen in this Pascal code1:
If Money>Price Then
If Doors=4 Then
If Color='Red' Then
Write('I think you should buy this car');
However, you can use Boolean Operators to make things easier, like so:
If (Money>Price)And(Doors=4)And(Color='Red') Then
Write('I think you should buy this car');
Both codes will have the same effect - only if all three conditions are true, the quoted line will be printed on the screen.