In this box will be the voice-over whiteboard presentation. Until then, I will write.

The most often used control statement is the If statement. There are lots of different forms of the If statement in Perl, or more exactly, there are a lot of different ways of getting If statement behavoir.

The If statement runs a block of code only in the case where the controlling logical expression gives true. The If statement can have an optional Else statement following it. The code block associated with the else statement is run only if the code block associated with the if statement is not, and vice a versa. Either one code block or the other is run.

An if/else statement pair is written:

  [the keyword if] 
           [a logical expression] 
              [a block of code]
  [the keywork else}
           [a block of code]
The precise syntax will have the logical expression enclosed in parenthesis and the code blocks are enclosed in curly braces.

» Try the example code in the window and see what it does.

The logical expression in the example code is $i%2==0. The percentage operator takes the remainder when the value in variable i is divided by 2. If a number is even, there is no remainder if that number is divided by 2, that is, the remainder is 0. The logical expression first evaluates the remainder and then compares the answer to 0. In the case of an even value in i, the expression is true.

If the expression is true, then block following the if keyword is executed, else it is not. Since there is an else clause, if the if block is not executed, then the else block is.

» Modify the program to check whether the variable contains a value divisible by 3. If it is, in prints out that it is divisiable by three; else it prints out that it is not divisible by three.

We now give you a challenging assignment.

» Modify the program so that if the value is not divisible by three, it prints out whether the remainder is 1 or 2.

P.S.: you are not allowed to do:

   $j = $i%2 ;
   print "the remainder of $i when divided by 3 is $j\n".
That's a good solution, but we are trying to learn something else. What I am hoping you do is to put an if/else statement inside the else statement of the program you have already written.

When putting code blocks inside code blocks, watch your indentation. Keep adding to the indentation with every enclosed block.

The output goes here

Discussion

This is where the discussion goes. It's a long box underneath both the other boxes.