Control Structures - Second Style

In this chapter we are going to learn about the second style of control structures provided by the Ring programming language.

Branching

  • If Statement

Syntax:

if Expression
        Block of statements
elseif Expression
        Block of statements
else
        Block of statements
end

Example:

put "
        Main Menu
        ---------
        (1) Say Hello
        (2) About
        (3) Exit

    " get nOption

if nOption = 1  put "Enter your name : " get name put "Hello " + name + nl
elseif nOption = 2 put "Sample : using if statement" + nl
elseif nOption = 3 bye
else put "bad option..." + nl
end
  • Switch Statement

Syntax:

switch Expression
case Expression
        Block of statements
else
        Block of statements
end

Example:

Put "
        Main Menu
        ---------
        (1) Say Hello
        (2) About
        (3) Exit

    " Get nOption

Switch nOption
Case 1 Put "Enter your name : " Get name Put "Hello " + name + nl
Case 2 Put "Sample : using switch statement" + nl
Case 3 Bye
Else Put "bad option..." + nl
End

Looping

  • While Loop

Syntax:

while Expression
        Block of statements
end

Example:

While True

        Put "
                Main Menu
                ---------
                (1) Say Hello
                (2) About
                (3) Exit

            " Get nOption

        Switch nOption
        Case 1
                Put "Enter your name : "
                Get name
                Put "Hello " + name + nl
        Case 2
                Put "Sample : using while loop" + nl
        Case 3
                Bye
        Else
                Put "bad option..." + nl
        End
End
  • For Loop

Syntax:

for identifier=expression to expression [step expression]
        Block of statements
end

Example:

# print numbers from 1 to 10
for x = 1 to 10  put x + nl  end

Example:

# Dynamic loop
Put "Start : " get nStart  nStart= 0+nStart
Put "End   : " get nEnd    nEnd  = 0+nEnd
Put "Step  : " get nStep   nStep = 0+nStep
For x = nStart to nEnd Step nStep
        Put x + nl
End

Example:

# print even numbers from 0 to 10
for x = 0 to 10 step 2
        Put x + nl
end

Example:

# print even numbers from 10 to 0
for x = 10 to 0 step -2
        put x + nl
end
  • For in Loop

Syntax:

for identifier in List/String  [step expression]
        Block of statements
end

Example:

aList = 1:10    # create list contains numbers from 1 to 10
for x in aList  put x + nl  end  # print numbers from 1 to 10

Exceptions

try
        Block of statements
catch
        Block of statements
end