Previous: Functions

# Workshop 3: Branches and Loops

You will use "if" statements when you want your script to make decisions - meaning that it behaves differently depending on some conditions, like user input, a random number, the result of a mathematical operation, a crossing of two indicators, etc. Here's the basic form of the "if" statement:

if(some condition is true)
do_something(); // execute this command (a single command!)

or

if(some condition is true)
{
// execute one or several commands that are placed inside the curly brackets
}

A more complex form of the "if" instruction is listed below:

if(some condition is true)
{
// execute one or several commands that are placed inside the curly brackets
} else {
// execute one or several commands that are placed inside these curly brackets
}

The instructions placed inside the "else" part are executed only if "some condition" is not true. Here's a practical example:

if(my_age > 65)
income = 2000;
else // age less than or equal to 65?
income = 3000;

Income can be either 2000 or 3000 because only one of the branches will be executed. The conditional parts of the code are called "branches" because several nested if instructions can look like a tree with the root at the first "if" and many branches of which only one is executed.

We indented the lines after the "if" and between the winged brackets. The C language does not care how you indent lines or if you write a command on the same or on a new line, but we do that for clarity. The code reads easier if dependent lines are indented.

Let's draw some conclusions:

► "if" branching statements start with the if keyword followed by a pair of parentheses;

the parentheses contain a comparison, or any other expression ("some condition") that can be true or false;

if the expression is true, the following instruction or the set of instructions placed inside the first pair of curly brackets is executed;

if the expression is false and we don't use "else", the set of instructions placed between the curly brackets is skipped (it isn't executed);

if the expression is false and we are using the "else" branch as well, the set of instructions placed inside the first pair of curly brackets is skipped, and the set of instructions placed inside the second pair of curly brackets is executed.

indentation and lines are not needed for the language, but make code easier readable.

Another example:

```function main()
{
var profit = slider(3,50,0,200,"Profit",0);
if(profit > 100)
printf("Enough!");
else
printf("Not enough!");
}```

When you now click [Test] to run the script again, you'll notice that the bottom slider gets the label "Profit". Move it all the way to the right, so that 200 appears in the small window, and click [Test] again. You can see that the result is now different. The slider() function has put its return value - which is the value from the bottom slider - into the profit variable, and thus the if(..) condition became true as the value was bigger than 100. You can see details of the slider function in the manual. Now let's assume that you want to do something only when two different conditions are fulfilled:

```function main()
{
var profit = slider(3,50,0,200,"Profit",0);
var loss = slider(2,25,0,200,"Loss",0);
if((profit > 50) and (loss == 0))
printf("Enough!");
else
printf("Not enough!");
}```

Now two sliders are involved. We can combine two conditions using the "and" keyword. That means both conditions must be true for the combination to be true. There is also an "or" keyword when only one of the conditions needs be true.**

The parentheses around (profit > 50) and (loss == 0) matter. Use parentheses to make sure that the program calculates in the same order that we want, and make sure that you have as many opening as closing parentheses! A missing parentheses at the end of a line is one of the most frequent reasons of compiler error messages. The computer will usually complain about an error in the following line because it's there looking for the missing parenthesis. That was the first tip.

Mind the double equals in "loss == 0 ". Whenever you compare two expressions (loss and 0 in the example above) you have to use "==" instead of "=", because a line of code that looks like this:

if(loss = 0)
{
// do some stuff
}

will set loss to zero instead of comparing loss with zero!

Use the '==' comparison with care when comparing var variables. If a computer calculates a mathematical expression, the result is usually inaccurate due to the limited floating point precision. Instead of 0.333333333..., dividing 1 by 3 results in 0.3333329856. Thus a comparison will come out false. When comparing values with many decimals, such as prices, it's highly unlikely that two such values will be ever exactly equal. Normally you'll only use 'greater' or 'smaller' comparisons (< or >) with var variables. This problem does not affect int variables, as they have no decimals and can indeed be exactly equal.

### Expressions

An (arithmetic) expression is a sequence of variables, numbers, operators, etc that are linked together. You can have simple expressions that look like the one below:

if(indicator > 50) // simple expression inside the parenthesis
{
// do something
}

Or you can have arbitrary complicated expressions that are a combination of sub-expressions:

if((factor1*indicator1 > 50)  and  (indicator2 < 35)  and  (volatility < 10)) // more complicated expression
{
// do something
}

You can combine as many expressions as you want, using parentheses, just like in the example above. The same rules from your math classes apply here, too.

### While loops

An example of a "while loop":

while(my_money < 1000000)

The while statement has the same syntax as the if statement. There is some expression - in this case the condition that the variable my_money is less than a million - and a command that is executed when the expression is true. However, in the case of an if statement, the program whould then go on with executing the next command afterwards. In the case of a while statement, the program "jumps back" to the while condition and tests it again. If it's still true, the command is executed again. And the while condition is then tested again. And so on. This process is repeated until the while expression eventually comes out false, or until eternity, whichever happens first.

A "loop" is called so because the program runs in a circle. Here's the basic form of the while loop:

while (some condition is true)
do_something(); // execute this command repeatedly until the condition becomes false

or

while (some condition is true)
{
// execute all commands inside the curly brackets repeatedly until the condition becomes false
}

Note that whatever the commands do, they must somehow affect the while condition, because when the condition never changes, we have an "infinite loop" that never ends!

Here's a practical example of a while loop. Run this in Zorro:

```function main()
{
int n = 0;
while(n < 10) {
n = n + 1;
printf("%i ",n);
}
} ```

This little program adds 1 to the variable n, prints the variable to the message window, and repeats this until n is 10.

Loops are very useful when something has to be done repeatedly. For instance, when we want to execute the same trade algorithm several times, each time with a different asset. This way we can create a strategy that trades with a portfolio of assets.

### And there's more...

We are now at the end of the three basic workshops that teach general programming. In the next workshops we'll begin with developing trade strategies; you've already learned all programming stuff that you'll need for those lessons. But there's far more to programming - we haven't touched yet concepts such as macros, pointers, arrays, structs, classes, or the Windows API. lite-C also supports some elements from C++, the 'big brother' of C - such as methods or function overloading.

If you want, you can learn 'real' programming beyond the scope of trade strategies. Buy a C book or go through a free online C tutorial, such as Sam's Teach Yourself C in 24 Hours. You can also join the Gamestudio community that uses Zorro's lite-C language for programming small or large computer games. Check out how a 'real' C program looks like: open and run the script Mandelbrot. It has nothing to do with trading and you will probably not understand yet much of the code inside. It is a normal Windows graphics program. Don't worry, trading strategies won't be this complicated - it just shows that programming has a lot more depth and can be a lot more fun even without earning money with it.

** C/C++ programmers might wonder why they have to use and and or instead of the familiar operators && and ||. Don't worry, all C operators work as before, we're just using easier-to-memorize operators for beginner's sake.