MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Code blocks

To execute more than one statement in a conditional, you may use code blocks, which are sequences of statements packaged together between braces — { and }. Code blocks behave just as they do in Java, and can be used in the same places.

The most general form of an if statement can be written as follows:

  if (true or false expression) 
  {
    statement_1a
    statement_1b
    statement_1c
    ...
    statement_1n
  }
    

and

      
  if (true or false expression) 
  {
    statement_1a
    statement_1b
    statement_1c
    ...
    statement_1n
  }
  else
  {
    statement_2a
    statement_2b
    statement_2c
    ...
    statement_2n
  }
      

Let us extend the shopping example from the introduction to the if statement to provide the user with a table of possible purchases if they are a member of a shopping club.

Exercise 8

Remembering that you can dynamically create the content of an HTML document using the document.write() method, change the shopping example to ask for confirmation of, say membership of an Italian food shopping club. If the user clicks OK, they should be presented with a table of shopping choices, as in the following:

(Hint: you can include statements that use document.write() to generate the table, e.g. document.write('<TABLE BORDER=1>'); document.write('<CAPTION><B>...).)

If the user clicks Cancel, they should be asked to join the club and be presented with a link to a registration URL (you may use an arbitrary URL) as below:

You can find a discussion of this exercise at the end of the unit.