# Class 2: Expressions, flow control

## Expressions

Make use of operators and variables to form small statements..

```
// overall evaluation happens right to left
int \$i = \$j + \$k;
float \$f = 2.718;
int \$ang = 375 % 360; // modulus
int \$k = (\$j == \$r); // always 0 or 1
int \$v = ( (\$f == \$a) && (\$g < \$s) );
\$i = 45; // OK
45 = \$i; // *not* OK!
\$i = (\$f==3.1415); // OK
\$i = (3.1415==\$f); // also OK

```

## Flow control - overall idea

• they make “real” programming happen
• can be deeply nested (telescoped) inside each other
• express program logic

## Flow control - two (or three, including "recursion") ways

### Looping

Two (three) ways:
• 'for' statement: two versions
• 'while' statement

### Branching

Three variations:
• 'if-else' – binary branching
• 'case' – multiway branches
• conditional assignment, using the '?' operator (and the ':' operator)
```// if (\$a==6)\$k=5;else \$k=556;
int \$k = (\$a==6)?5:556;
```

#### Fun

"Should I stay or should I go?"

Courtesy of Eric Keller:

```if (\$go)
{
\$trouble = 1;
}
else
{
\$trouble = \$trouble*2;
}
```

### Recursion

Another powerful, elegant way to manipulate program flow is recursion, which MEL supports. Here's an example:
```proc int iterativeFactorial(int \$n)
{
int \$result = 1, \$i;

for(\$i=1;\$i<=\$n;\$i++)
{
\$result *= \$i;
}

return \$result;
}// iterativeFactorial(()

// run the non-recursive (loop-based) version:
int \$rslt = iterativeFactorial(6);

proc int recursiveFactorial(int \$n)
{
if(\$n==0)
return 1; // 0!=1, by definition
else
return (\$n*recursiveFactorial(\$n-1)); // recursion!!
}// recursiveFactorial(()

// test the recursive version
int \$rslt = recursiveFactorial(6);
```
Recursion is very good for creating certain kinds of snowflake curves, tiling patterns, cloud/fireball shapes, plants/trees, etc.

## Flow control - summary

```
To recap, ‘flow’ refers to flow of program statements,
which really reflect flow of logic.

Before you write a single line of MEL, make sure that
you can write your program out in pseudocode
and explain it to your non-technical neighbor.

DESIGN, **then** CODE.
Coding is the “easy” part..

```

## Extras

```// "horn"
int \$theta;
for(\$theta=0;\$theta<360;\$theta+=10)
{
float \$r=1.0;
float \$x = \$r*cos(\$theta*3.14159278/180);
float \$y = \$r*sin(\$theta*3.14159278/180);
sphere -p \$x \$y 0.0 -r (.05+(\$theta*.001));
}

// grid of spheres
for(\$i=0;\$i<5;\$i++)
{
for(\$j=0;\$j<5;\$j++)
{
sphere -r .1 -p \$i \$j 0.0;
}
}
```
```// box of spheres
proc boxOfSpheres(int \$nS, float \$rMin, float \$rMax,int \$size)
{
int \$i;
for(\$i=0;\$i<\$nS;\$i++)
{
float \$x = rand(-\$size,\$size);
float \$y = rand(-\$size,\$size);
float \$z = rand(-\$size,\$size);
float \$r = rand(\$rMin,\$rMax);
print("rad is " + \$r + "\n");
sphere -p \$x \$y \$z -r \$r;
}
}// boxOfSpheres

// usage:
boxOfSpheres(100,1,2,10);
```