DPUSER - The Next Generation

# Conditional statements, Loops and Statement blocks

DPUSER provides language elements that allow to take action only when a certain condition is met (commonly called `if-then-else` statements). Also, you can construct loops using the `for` and the `while` constructs.

- `if-then-else` statements
- `for` and `while` loops

## Conditional statements

There are two ways to evaluate conditional statements in DPUSER, as well as two kinds of loops. Both have in common that they can execute statement blocks. The general syntax for a conditional statement is:

> `if (boolean) {`
> `do something`
> `...`
> `} else {`
> `do something else`
> `...`
> `}`

The else part is optional.
The second way to evaluate a conditional statement is using the following:

> `boolean ? do this : do that`

### Examples

> `if (a == 1) {`
> `print "A is one"`
> `} else {`
> `print "A is not one but " + a`
> `}`

> The same thing in one line:
> `print "A is " + (a == 1 ? "one" : "not one but " + a)`

Note that nesting conditional statements is not allowed. Therefore, the following code creates a syntax error:

> `if (a == 1) {`
> `print "one"`
> `} else if (a == 2) { <== THIS IS NOT ALLOWED`
> `print "two"`
> `} else {`
> `print "neither one or two"`
> `}`

If you want to do something like this, do the following:

> `if (a == 1) {`
> `print "one"`
> `} else {`
> `if (a == 2) {`
> `print "two"`
> `} else {`
> `print "neither one or two"`
> `}`
> `}`

Or, as a (complicated) one-liner, since nesting is allowed using the second construct:

> `print (a == 1 ? "one" : (a == 2 ? "two" : "neither one or two"))`
> (You can leave out all the parentesis, but for readibility it is better to use them)

## Loops

A loop can be constructed using the `for` as well as the `while` statements. The general syntax for the `for` loop is:

> `for (start_condition; boolean; change_condition) {`
> `do something`
> `...`
> `}`

A `while` loop is constructed like this:

> `while (condition) {`
> `do something`
> `...`
> `}`

### Examples

Print out all numbers from 1 to 9

> `for (i = 1; i < 10; i++) print i`

> `i = 1`
> `while (i < 10) {`
> `print i`
> `i++`
> `}`

Note that in the second example, it is easy to create an endless loop if you forget the `i++` statement. You can always use curly brackets to execute more than one statement in a loop or as a result of a conditional statement.

Assign the ASCII character set to a string variable:

> `s = ""`
> `for (i = 32; i <= 255; i++) s += char(i)`