IF in Scol » History » Version 1
iri, 09/24/2012 11:54 PM
| 1 | 1 | iri | h1. IF in Scol |
|---|---|---|---|
| 2 | |||
| 3 | *if* <condition> *then* <instructions> *else* <instructions> |
||
| 4 | |||
| 5 | else is +imperative+. |
||
| 6 | |||
| 7 | More complicated : |
||
| 8 | |||
| 9 | <pre> |
||
| 10 | if (((condition1) && (condition2)) || (condition3)) then |
||
| 11 | ( |
||
| 12 | instructions |
||
| 13 | ) |
||
| 14 | else if (condition4) then |
||
| 15 | ( |
||
| 16 | instructions |
||
| 17 | ) |
||
| 18 | else |
||
| 19 | ( |
||
| 20 | instructions |
||
| 21 | ) |
||
| 22 | </pre> |
||
| 23 | |||
| 24 | For a simple condition, like x < 5, the () is not imperative but recommended. For others cases, ( ) are needed. |
||
| 25 | |||
| 26 | Be careful, if <condition> then <instructions> else <instructions> is one instruction ! There is only a semicolon at the end of the last instruction of else block. |
||
| 27 | |||
| 28 | Example : |
||
| 29 | |||
| 30 | <pre> |
||
| 31 | fun main ()= |
||
| 32 | _showconsole; |
||
| 33 | |||
| 34 | srand time; |
||
| 35 | let ((rand&255)*100)>>8 -> x in // randomized value |
||
| 36 | if (x < 10) then |
||
| 37 | _fooS "x is small" // no semicolon ! |
||
| 38 | else if (x > 90) then |
||
| 39 | _fooS "x is big" // no semicolon ! |
||
| 40 | else |
||
| 41 | _fooS "x is medium"; // semicolon ! |
||
| 42 | 0;; |
||
| 43 | </pre> |
||
| 44 | |||
| 45 | other example : |
||
| 46 | |||
| 47 | <pre> |
||
| 48 | fun main ()= |
||
| 49 | _showconsole; |
||
| 50 | |||
| 51 | srand time; |
||
| 52 | let ((rand&255)*100)>>8 -> x in // randomized value |
||
| 53 | let mod x 2 -> m in // modulo x by 2 |
||
| 54 | if m == 0 then |
||
| 55 | ( |
||
| 56 | _fooS strcat "x = " itoa x; |
||
| 57 | _fooS strcat "x is even"; |
||
| 58 | ) // no semicolon ! |
||
| 59 | else |
||
| 60 | ( |
||
| 61 | _fooS strcat "x = " itoa x; |
||
| 62 | _fooS strcat "x is uneven"; |
||
| 63 | ); // semicolon ! |
||
| 64 | 0;; |
||
| 65 | </pre> |
||
| 66 | |||
| 67 | |||
| 68 | License : "CC-BY-SA-2.0":https://creativecommons.org/licenses/by-sa/2.0/ |
||
| 69 | Tutorial by iri |
||
| 70 | Updated by / |