Conditionals: The IF statement

In our first 2 chapters we looked at variables. This chapter we’ll look at conditionals.  Conditional statements in programs ask a question and much like human responses  will return a true or false. Combined with loops and variables they are incredibly powerful.

The conditional operator you will see in most computer languages is the ‘IF’ statement and the majority of languages simply use ‘IF’. Along with the IF statement are ‘comparison operators’. You will have seen these in maths: greater than, less than, equal to and so on.

Greater Than: >

Less Than: <

Equal To: = (sometimes == in some languages)

Equal To OR Greater Than: >=

Equal To OR Less Than: <=

Not Equal To: !=

Not: !

The ! signifies the opposite or negative. So:

if 6=7 returns false

if 6 != 7 returns true

When using the IF statement we need to tell the computer to do something if the return statement is true. For this we ususlly include brackets {}.

if 6<7{
print “6 is less than 7″
}

If the above statement is true then the computer will run the code within the brackets, if not then it will jump to the end bracket and continue from there.
We can also tell the computer to do something if the statement is false or even ask another question within the same conditional.

if 6>7{
print “6 is greater than 7″
}
else if 6==7 {
print “6 is equal to 7″
}
else {
print “6 is less than 7″
}

The above code asks if 6 is greater than 7 (false move to next question) is 6 equal to 7 (false again move to next) else means simply means if the above aren’t true run these brackets. Below is a good example when you’ll need an else:

if pinEntered = accountPin {
print “Your account balance is £” + balance
}
else {
print “Pin entered is wrong”
}

Above you saw an example where a pin entered is checked and two different scenarios can occur. This also is the first example you’ve seen where variables are used in the IF statement. The pinEntered and accountPin are variables, most likely in this case to be integer variables. The balance variable would have been a decimal variable.
Conditional statements can also include strings and other variables. Many languages also wrap the statement in brackets for easier reading.

string nameEntered = “John”

if (nameEntered == “John”) {
print “Hello John”
}

but you must follow variable ‘type’ rules when using statements

int nameEntered = 1

if (nameEntered == “1″) {

print “Hello Number 1″

}

Output: Error type mismatch

The above statement should have been if (nameEntered == 1). The quotations indicate the variable is a string.

Next chapter we’ll look at the IF statement and other conditionals in greater depth.

Leave a Reply

You must be logged in to post a comment.