Small Basic Curriculum: Lesson 1.5: Branching and Subroutines

Small Basic Curriculum: Lesson 1.5: Branching and Subroutines

Small Basic > Curriculum > Online > Lesson 1.5: Branching and Subroutines


 
Estimated time to complete this lesson: 1 hour

 

Code Branches and Subroutines

In this lesson, you will learn how to:

  • Branch your code by using Goto statements.
  • Create subroutines by using Sub and EndSub statements.

Branching

As you know, the computer runs a program by reading and processing the statements line by line, one at a time.

Sometimes, you may want the computer to break the flow and jump to another line of code while the program is running.

TextWindow.Write("Enter a number: ")
number = TextWindow.ReadNumber()
remainder = Math.Remainder(number, 2)
If remainder = 0 Then
TextWindow.WriteLine("The number is even.")
Else
TextWindow.WriteLine("The number is odd.")
EndIf

 

You can instruct the computer to process a line of code out of sequence if you use the Goto statement.

j = 1
lineQ:
TextWindow.WriteLine(j)
j =  j + 1
If j < 30 Then
Goto lineQ
EndIf

 

Branching in Small Basic Programs

Let’s examine the Goto statement and its various parts by writing a program.

j = 1
lineQ:
TextWindow.WriteLine(j)
j =  j + 1
If j < 10 Then
Goto lineQ
EndIf

 

In this program, the lineQ: statement is called a label, which is similar to a bookmark. You can add as many labels as you want and name them whatever you want, as long as you don’t use the same name more than once.

The Goto statement instructs the computer to run the statements after the lineQ: label again only if the condition in the If statement is true.

This is the output you will see:

Branching in Small Basic Programs

In the first line of this program, you create a variable that is named j, and you set its value to 1.

Then you create a label that is named lineQ: with a colon (:) at the end.

In the next line, you tell the computer to display the value of the j variable on the screen.

Then you increase the value of the j variable by 1.

In the fourth line, you determine whether the value of the j variable is smaller than 10.

--If it is, you tell the computer to repeat the lines of code that follow the lineQ: label. In other words, you tell the computer to display the value of the j variable, increase its value by 1, and then determine whether that value is smaller than 10.

--If the value of the j variable is not smaller than 10, you tell the computer to continue to the next part of the program (or to stop running the program if no more code exists).

You can also use the Goto statement to make a program run forever.

Let’s see how Goto statements work by adding one to a familiar program.

start:
TextWindow.WriteLine("How many members are in your family?")
number = TextWindow.ReadNumber()
remainder = Math.Remainder(number, 2)
If remainder = 0 Then
TextWindow.WriteLine("Your family has an even number of members.")
Else
TextWindow.WriteLine("Your family has an odd number of members.")
EndIf
Goto start

 

This program will continue to run until someone clicks the Close (X) button in the top-right corner of the text window.

This is the output you will see:

Branching in Small Basic Programs

Warning: If you use Goto statements a lot, your code will be difficult to understand and to correct. Although these statements are useful sometimes, you should try to structure your programs so that you rarely use Goto statements.

Subroutines in Small Basic Programs

When we write programs, we often want the computer to run certain statements more than once. You can avoid writing the same statements over and over if you use subroutines in your programs.

By using a subroutine,  you can run one or more statements with a single instruction. To create a subroutine, you use the Sub keyword, and then you give the subroutine a specific name. You end the subroutine by using the EndSub keyword.

Look at the following subroutine named PrintHour, which opens a text window and displays the current hour.

Sub Print Hour
TextWindow.WriteLine(Clock.Hour)
EndSub

 

Let’s gain a better understanding of subroutines by writing another program…

While i < 5
TextWindow.WriteLine("Enter Dividend: ")
Dividend = TextWindow.Read()
TextWindow.WriteLine("Enter Divisor: ")
Divisor = TextWindow.Read()
Divide()
TextWindow.WriteLine("Your answer is: " + Answer)  
i = i + 1
EndWhile
Sub Divide
Answer = Dividend / Divisor    
EndSub

 

In this program, we use the Divide( ) statement to run (or “call”) the subroutine Divide from any location within the program.

This is the output you will see:

Subroutines in Small Basic Programs

If you use subroutines, your programs will be easier to read and understand than if you use Goto statements.

In this program, you write the Divide subroutine once, but you can run it from anywhere in the program.

When you instruct the computer to run a subroutine, you use a statement that contains the name of the subroutine followed by a set of open and close parentheses. When you use this type of statement, you are calling the subroutine.

Let’s Summarize…

Congratulations!

Now you know how to:

  • Create a branch by using a Goto statement.
  • Create a subroutine by using a Sub..EndSub statement.

Show What You Know

Write a program that opens a text window and then performs the following steps:

  1. Asks the user for the name, temperature, rain status, and wind status of 10 cities.
  2. Uses branching and subroutines to determine and display the total number of:
    • Cold Cities
    • Cool Cities
    • Warm Cities
    • Hot Cities
    • Rainy Cities
    • Windy Cities

To see the answers to these questions, go to the Answer Key page.

Next Lesson


PowerPoint Downloads

  

Sort by: Published Date | Most Recent | Most Useful
Comments
  • I think you should link every lesson with other lessons for better navigation.

  • Oh, I missed link at the bottom of article :)

  • Good idea. Yes, I plan to update the link at the bottom of the article and include bread crumb links at the top. Then I'll see if it needs more. Thanks!

  • I completed the breadcrumb links at the top and the "Next Lesson" link at the bottom. Thanks!

  • Great and thanks for keeping this series up to date. I really like it.

  • I felt like the end "show what you know" was quite a leap with this lesson.... maybe that's just me. Powerpoint downloads are a great addition though btw.

  • TeaWatch,

    What would you have liked to have seen in the lesson to make the "Show What You Know" part easier to accomplish?

    Thanks!

  • Hi Ed - I just felt that the "Show what you know" at the end of 1.5 was a bit of a stretch. But I'm going through it again tonight, the thing is, even by copying the code in the solution from the powerpoint I can't get it to work.

    here's the code :

    up:

    If i < 10 then

     TextWindow.WriteLine("")

     TextWindow.Write("What is the name of a city? ")

     city = TextWindow.Read()

     TextWindow.Write("How warm is that city (in degrees Celsius)? ")

     temp = TextWindow.Read()

     TextWindow.Write("Is it rainy (Y/N)? ")

     rainy = TextWindow.Read()

     TextWindow.Write("Is it windy (Y/N)? ")

     windy = TextWindow.Read()

     'Calling subroutines

     subtempCount()

     subrainyCount()  

     subwindyCount()

     i = i + 1  

     If i = 10 Then

       subOutput()

     EndIf

    EndIf

    Goto up

    Sub subtempCount

     If temp <= 5 Then

           ColdCount = ColdCount + 1

     ElseIf temp <= 15 Then

           CoolCount = CoolCount + 1      

     ElseIf temp <= 25 Then

           WarmCount = WarmCount + 1    

     Else

           HotCount = HotCount + 1    

     EndIf  

    EndSub

    Sub subRainyCount

       If Rainy = "y" Or Rainy = "Y" Then

          RainyCount = RainyCount + 1

       EndIf

    EndSub

  • Been playing around with this again - I can get it so the window actually opens now but I can't display the totals of the different rainy / windy etc after the required amount of entries have been made....

  • Hi!

    With some inspiration on the approach from the TeaWatch`s comment I managed to get the thing running.

    Made some changes to the city count - it`s user defined instead of the 10 from the preset.

    SmallBasic is Fun!

    'Outputs a summary of weather conditions on a user defined number of cities.

    'User has to intput number of cities, the name, temperature, wind and rain conditions.

    TextWindow.Title = "Weather report""

    windycount = 0

    raincount = 0

    hotcount = 0

    warmcount = 0

    coldcount = 0

    TextWindow.WriteLine("How many cities to report? ")

    city_nb = TextWindow.ReadNumber()'An addition - the user can choose the number of cities instead of the preset 10

    While i < city_nb

     TextWindow.WriteLine("City name: ")

     City = TextWindow.Read()

     TextWindow.WriteLine("Enter temperature(C): ")

     temp = TextWindow.ReadNumber()

     TextWindow.WriteLine("Is it windy?(Y/N)")

     Wind =  TextWindow.Read()

     TextWindow.WriteLine("Is it raining?(Y/N)")

     Rain = TextWindow.Read()

     wind_sub()

     rain_sub()

     temp_sub()

     i = i + 1

     If i = city_nb Then

       sub_output()

     EndIf

    EndWhile

    wind_sub()

    rain_sub()

    Sub wind_sub

     If Wind = "Y" or Wind = "y" Then

       windycount = windycount + 1

     EndIf

    EndSub

    Sub rain_sub

     If Rain = "Y" or Rain = "y" Then

       raincount = raincount + 1

     EndIf

    EndSub

    Sub temp_sub

     If temp <= 5 Then

       coldcount = coldcount + 1

     ElseIf temp <= 15 then

       warmcount = warmcount + 1

     Else

       hotcount = hotcount + 1

     EndIf

    EndSub

    Sub sub_output

     TextWindow.WriteLine("Number of rainy cities: " + raincount)

     TextWindow.WriteLine("Number of windy cities: " + windycount)

     TextWindow.WriteLine("Number of cold cities: " + coldcount)

     TextWindow.WriteLine("Number of warm cities: " + warmcount)

     TextWindow.WriteLine("Number of hot cities: " + hotcount)

    EndSub

Page 1 of 1 (10 items)