CSCI 201 Introduction to Algorithm Design home | homework index | labs index SPRING 2007

Conditional Execution and Relational Operators

This lab will test your ability to use Java's conditional statements and relational operators while you draw some flags.

The if-statement

One of the simplest form of conditional statement is the `if` statement. This statement directly translates into: if a test is true, then do this, else do that - decisions that you make each and every day of your life. Some examples:

• If the traffic light is red, then stop, else go.
• If you are thirsty, then get a drink, else don't get a drink.
• If the stock price is greater than \$45.50, then sell, else don't sell.
• If X is greater than 5, then output X, else add 1 to X.

The last statement above is very close to what computers do, here is that statement translated into Java:

```  if ( X > 5 ) {                 // IF X is greater than 5
System.out.println( X );   // THEN Output X
} else {                       // ELSE
X = X + 1;                 // Add 1 to X
}
```

Notice, first comes the word `if`, then a test within parenthesis, then the true, or then, block of code enclosed in curly braces ({}),  then the false, or else, block of code enclosed in curly braces. The `else` portion of the statement can be omitted, in which case, nothing is done if the condition is false.

As it turns out, in those cases in which either the true or else block is a single statement long, the curly braces can be omitted. This allows the conditional statement shown above to be re-written as follows:

```  if ( X > 5 )                // IF X is greater than 5
System.out.println( X );      // THEN Output X
else                           // ELSE
X = X + 1;                    // Add 1 to X
```

Unfortunately, even experienced programs can make mistakes when they avoid the braces, so we suggest you try to use them, especially when writing your first few programs.

Programming with style

It is very important that you indent, with a consistent number of spaces, the then and else blocks of your code. Condition expressions with messy indentations are extremely difficult to comprehend and are always the sign of a poorly designed program. Turning in a programming assignment with poor indentation is certain to lower your grade.

```if ( X > 5 ) {
System.out.println( X ); ```
```}
else {
X = X + 1;
}
```

Stack N' Heap

Step through the following example to see a couple of conditional statements in action.

 Code int test = 15; if (test > 30) {     System.out.println("one"); } if (test == 15) {     System.out.println("two"); } else {     System.out.println("Not two"); } Stack Heap Temporary

Relational operators

What makes conditional statements so powerful is that almost any code can go in the then or else blocks. But to use an `if` statement, you must know how to correctly specify a test. The test, which is always placed in parenthesis, must be an expression that evaluates to either a `boolean` values, that is, `true` or `false`. Relational operators are binary operators that compare two values and generate a boolean result. The following table contains the relational operators of Java.

 `x < y` x is less than y `x <= y` x is less than or equal to y `x > y` x is greater than y `x >= y` x is greater than or equal to y `x == y` x is equal to y `x != y` x is not equal to y

Logical operators

But that's not all. You can also use logical operators to create conditions. They allow you to execute blocks under more complex conditions, such as when Income is greater than 15000 and Income is less than 40000. Java pretty much sticks with the the same three operators defined by George Boole by 1854 in "An Investigation Into the Laws of Thought, on Which are founded the Mathematical Theories of Logic and Probabilities". However, Java requires these operators to be written in a most peculiar fashion.

 `P && Q` True only when both P and Q are true `P || Q` True if at least one of P and Q are true `! P` True only if P is false

Because `&&` and `||` have a lower level of precedence than the relational operators, you can write Java tests like "```Income > 15000 && Income < 4000```" without using parenthesis. Following the convention of decades of logicians, `&&` has a higher precedence than `||`.

Download Flag.zip, a ZIP file containing a NetBeans project named Flag and unZIP this project into your csci/201 directory. Try to make your Projects panel look something like the following picture before continuing.

Modifying the project

The framework for the project

The interface for this lab is the `SpecFlag` interface of the `edu.unca.cs.csci201.labaids` package.

```package edu.unca.cs.csci201.labaids;

import java.awt.Color ;

public interface SpecFlag {
public int getHeight() ;
public int getWidth()  ;
public Color TestFunc(int x, int y) ;
}
```

To complete this interface you will have to complete three methods. The first two return the width and height of the flag in equal-sized tiles or cells. Usually, these methods are one-liners. The real action is in `TestFunc`, the third method. `TestFunc` is passed two integers as input and returns a Java color. The two integers are the x and y co-ordinates of a cell within the flag. The color returned by `TestFunc` is used to paint the cell located at those coordinates.

Scroll through the file Main.java to the code for the class `Haiti`.

```private static class Haiti implements SpecFlag {
private static final int Height = 20 ;
private static final int Width  = 30 ;
public int getHeight() {
return Height ;
}
public int getWidth()  {
return Width ;
}
public Color TestFunc(int x, int y) {
if (y<10)
return Color.BLUE ;
else
return Color.RED ;
}
}
```

The class begins with two lines of code to set the variables `Height` and `width`. The `getHeight` and `getWidth` methods return these values to the Java code that displays the flag. In this case the flag display area is to be partitioned into a grid of 30 by 20 rectangles. This means the that `TestFunc` method will be called 600 times with `x` values ranging from 0 to 29 and with `y` values ranging from 0 to 19. For each of these input combinations, `TestFunc` returns a Java `Color` to be used to paint a small rectangle of the screen. Our sample `TestFunc` paints the top half of the display area blue and the bottom half red.

You are to modify the classes `checkers`, `Ireland`, `North Carolina`, `USA`, `Japan`, and `Jamaica` to display some nifty flags. In order to do this, you will need to write conditional statements that use the relational and logical operators described in your textbook.

The `checkers` class should return the usual 8 by 8 checkerboard of alternating black and red places. You'll find it useful to use the remainder, `%`, operator here.

The flag of Ireland is three equal vertical strips of green, white, and orange. You can consult the on-line World Flag Database for a bit more information.

For the Ireland flag, like those of North Carolina and the United States, you really ought to modify the default values of `Height` and `Width` to make the problem much easier to program. Be logical in your choices. If a flag has 11 horizontal stripes, 8 is not a good choice for `Height`.

For the flag of the state of North Carolina, you do not need to show the letters, star, or banners within the field of blue. For the flag of the United States, you do not need to show the stars, but you better show the thirteen alternating red and white stripes.

The flag of Japan contains a round red circle. With our cells you can't display this exactly, but you can give an approximation. By the way, in case you don't remember: A point (xy) is within a circle of radius r centered at (midXmidY), if (x-midX)2+ (y-midY)2 is less than r2.