Wiki

Changes between Version 1 and Version 2 of IfStatement

Show
Ignore:
Timestamp:
12/20/10 02:40:49 (13 years ago)
Author:
todd.a
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • IfStatement

    v1 v2  
    1 The '''while''' statement is used to repeatedly execute code while a condition is true. 
     1The if statement is used to conditionally execute code. 
    22=== Grammar === 
    33{{{ 
    4 while-statement = 
    5     [post] while <expression> 
     4if-statement = 
     5    if <expression> 
    66        <statements> 
     7    (else if <expression> 
     8        <statements>)* 
     9    [else 
     10        <statements>] 
    711}}} 
    812 
    9 Without the '''post''', the expression is checked first and while true, the statements are repeatedly executed. If the expression is false the first time, the statements will not execute. With the '''post''', the condition is checked after the statements execute, so the statements will execute at least once. 
    10  
    11 Inside the statements, a '''break''' statement will exit the loop and a '''continue''' statement will skip the remaining statements and evaluate the expression again. In either case, an '''if''' statement is used to control when the loop is broken or continued (otherwise it would be pointless to have further statements in the loop). 
     13Each expression is evaluated in order until one evaluates as true. Then the statements belonging to that expression are executed. If no expressions evaluate to true and the else portion is present then its statements are executed. Only one set of statements is ever executed and without an '''else''' it is possible that no statements are ever executed. 
    1214 
    1315{{{ 
    1416#!cobra 
    1517# Example 1 
    16 while obj.someCondition 
    17     obj.process 
     18if name 
     19    print 'Hello, [name].' 
    1820 
    1921# Example 2 
    20 while node 
    21     print node 
    22     node = node.next 
     22if name 
     23    print 'Hello, [name].' 
     24else 
     25    print "I don't know your name." 
    2326 
    2427# Example 3 
    25 while node 
    26     if not node.isActive 
    27         print 'skipping inactive node: [node]' 
    28         continue 
    29     print node 
    30     node.process 
    31     node = node.next 
    32  
    33 # Example 4 
    34 while true 
    35     input = Console.readLine 
    36     if input is nil or input.trim.toLower == 'exit' 
    37         break 
    38     .processInput(input) 
    39  
    40 # Example 5 
    41 post while line and line.trim == '' 
    42     line = stream.readLine 
     28if x < y 
     29    print 'x is smaller' 
     30else if x > y 
     31    print 'x is larger' 
     32else 
     33    print 'x and y are the same' 
    4334}}}