UNIHIVE

Study Hub UNIPORT CSC 180.1

CSC 180.1 · Introduction to Computer Science and BASIC Programming

Subroutines and subprograms

GOSUB and RETURN, why we break programs into modules, and SUB procedures in structured BASIC.

Our notes

1 min read

Why subroutines

Large problems are easier when split into smaller parts (modular or top-down design). A subroutine is a block of code that does one job and can be called from many places.
Benefits: no repeated code, easier testing and debugging, team work, clearer programs.

GOSUB and RETURN (classic BASIC)

GOSUB n jumps to line n and remembers where it came from; RETURN goes back to the line after the GOSUB.
10 INPUT "RADIUS"; R
20 GOSUB 100
30 PRINT "AREA ="; A
40 INPUT "ANOTHER RADIUS"; R
50 GOSUB 100
60 PRINT "AREA ="; A
70 END
100 REM SUBROUTINE: AREA OF A CIRCLE
110 LET A = 3.14159 * R^2
120 RETURN
Radii 1 and 2 give areas about 3.14 and 12.57.
The END at line 70 stops the program from "falling into" the subroutine.

ON...GOSUB (menus)

ON K GOSUB 200, 300, 400 calls the first, second or third subroutine when K is 1, 2 or 3; useful for menus.

Subprograms in structured BASIC (QBasic)

DECLARE SUB Greet (N$)
CALL Greet("ADA")
END

SUB Greet (N$)
  PRINT "WELCOME, "; N$
END SUB
Prints WELCOME, ADA. A SUB has its own local variables and receives values through parameters, so it does not clash with the main program. FUNCTION procedures return a value.

GOSUB against SUB

GOSUB subroutineSUB procedure
uses line numbersuses a name
shares all variables with the main programlocal variables, parameters
easy to misusesafer, structured

Top-down design example: a result program

  1. Main program: read student data, call subroutines, print.
  2. Subroutine 1: compute total and average.
  3. Subroutine 2: find the grade.
  4. Subroutine 3: print a report line.

Exams usually ask

  • Explain GOSUB and RETURN with an example program.
  • State the advantages of subroutines and modular programming.
  • Distinguish a subroutine from a user-defined function.

Common mistake

Leaving out END (or STOP) before the subroutine lines, so the program runs into the subroutine and then hits RETURN without GOSUB.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All CSC 180.1 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.