Image-7 If Logic

Our use of loops thus far have allowed us to write a little bit of code which is run for many data points. That's one big theme in computer code. The if-statement, the topic of this section, will add a second theme: the ability to write a true/false test to control if a bit of code runs or not. Combined with the loop, the if-statement will greatly expand what we can do with code.

Image X/Y Refresher


pixel.getX() pixel.getY() image.getWidth() image.getHeight()

If-Statement Demo

The if-statement has a true/false test which controls if some code is run or not. Here is an example if-statement shown inside a for-loop with the "stop.jpg" image.


image-logic-1

 

Flip Diagram


image showing x < 238 and x > 238 regions

If-Statement - You Try It


image-logic-2

 

Solution code

// a. if (pixel.getX() < 355) {
// b. if (pixel.getX() > 480) {
// c. if (pixel.getY() < 20) {
// d. if (pixel.getY() <> 20) {

image = new SimpleImage("stop.jpg");
for (pixel: image) {
  if (pixel.getX() < 355) {
    pixel.setRed(0);
    pixel.setGreen(0);
    pixel.setBlue(255);  // 0 here for black
  }
}
print(image);

Using image.getWidth() Expressions (optional)


image-logic-3