A Touch of Java

Part 2: control statements

PGSS Computer Science Core Slides

From yesterday we know how to alter memory with assignment statements and access memory with variables.

We now turn to control statements: conditional and iterative.

Conditional statements

Conditional statements allow us to execute a set of statements if a given condition holds.

```  if(n % i == 0) {
is_prime = 0;
}
i = i + 1;
```

If n % i is 0, then both is_prime = 0 and i = i + 1 are executed. If not, then the portion between braces is skipped and only the statement i = i + 1 is executed.

The braces enclose statements that will be skipped if the condition does not hold.

Conditions

The condition of if statements can be a complex expression. Here are some examples.

```k * k  <= 5                           true if k^2 <= 5
k == 2                                true if k is 2
k != 1                                true if k is not 1
k > 0 && done == 0                    true if k > 0 and done is 0
k < 5 || k > i                        true if k < 5 or k > i
a[0] == a[1] || k >= 2 && k <= 5      (&& precedes ||)
(a[0] == a[1] || k >= 2) && k <= 5
```

Else...

We also often want to do one thing if a condition holds and another if not. Java lets us do this, using else.

```  if(n % i == 0) {
is_prime = 0;
} else {
i = i + 1;
}
```

If n % i is 0, then is_prime = 0 is executed. Otherwise i = i + 1 is executed. In any case, the next statement examined is the one following the last brace.

Iterative statements

An iterative statement allows a block of statements to be executed as long as a condition is true.

```  i = 2;
while(i * i <= 35 && 35 % i != 0) {
i = i + 1;
}
```

As long as i * i <= n and i does not divide n, we will increase i. Once the condition does not hold, execution skipes to after the closing brace.

Each execution of the enclosed statement block is called an iteration.

Out of the loop

Sometimes we want to break out of a loop in the middle. We do this with a break statement.

```  is_prime = 1;
i = 2;
while(i * i <= 35) {
if(35 % i == 0) {
is_prime = 0;
break;
}
i = i + 1;
}
```

A working version of Prime-Test-All, at last!

for loops

Since we so often want to try successive values of a variable, we have a simpler loop construct for this case.

```  for(i = 0; i < arr.length; i = i + 1) {
arr[i] = '0';
}
```

(The arr.length is a special expression whose value is the length of arr.)

This is equivalent to

```  i = 0;
while(i < arr.length) {
arr[i] = '0';
i = i + 1;
}
```

The for loop above puts a '0' in every element of arr.

```       +---+---+---+---+------+---+---+
arr: |'0'|'0'|'0'|'0'| ...  |'0'|'0'|
+---+---+---+---+------+---+---+
```