Skip to main content

Section 4.3 if statement

A if statement controls the flow of the program by executing one part of it if a certain condition is true (and possibly, executing another if the condition is false). The syntax is

if (condition)
    (what to do if the condition is true)
else
    (what to do if the condition is false)
end

The part with else is optional if you don't want to do anything special when the condition is false. The end is required, as with loops. Here is a simple script that tells the user if the number they entered is positive or negative.

x = input('x = ');
if x < 0
    disp('negative')
else
    disp('positive')
end

This code has a bug: if the user enters 0, the output is ‘positive’. To correct this, we need to put another if in the else clause. This is done with elseif:

x = input('x = ');
if x < 0
    disp('negative')
elseif x > 0
    disp('positive')
else 
    disp('zero')
end

Generally, conditions in while and if are of the form x (relation) y where the relation can be

  • < less than
  • > greater than
  • <= less than or equal
  • >= greater than or equal
  • == equal
  • ~= not equal

Warning: if (x=y) is incorrect, because a single = sign means assignment (make x equal to y), not equality (is x equal to y?). Also, we rarely need to test equality because it can fail because of tiny errors in computer arithmetics with non-integer numbers.

Write an if statement that tests whether \(0.1+0.2\) is equal to \(0.3\text{.}\)

Answer
if 0.1 + 0.2 == 0.3
    disp('equal')
else
    disp('not equal')
end

Running this code you will see a surprising result: “not equal”. We will consider this later. The point to be taken here is that testing for equality is practical only when both sides of == are integers.