Structured Programming in Basic Problems
© 1998 by Dr. Thomas W. MacFarland -- All Rights Reserved
Instructions: Review the following program and see if you can predict the outcome by completing a "pencil trace" of the code. Program output is provided at the end of this page. Compiler: The program was prepared using GWBasic, which requires the use of line numbers.
10 REM This program demonstrates a modular approach to
20 REM the use of a sorting algorithm.
30 GOSUB 1000 'Load the numbers
40 GOSUB 2000 'Sort the numbers
50 GOSUB 3000 'Print the numbers
99 END
1000 READ N
1010 DIM NUM(N)
1020 FOR ROW = 1 TO N
1030 READ NUM(ROW)
1040 NEXT ROW
1999 RETURN
2000 FOR BEGIN = 1 TO N-1
2010 SMALL = BEGIN
2020 FOR EXAMINE = BEGIN+1 TO N
2030 IF NUM(SMALL) > NUM(EXAMINE) THEN SMALL = EXAMINE
2040 NEXT EXAMINE
2050 TEMP = NUM(BEGIN)
2060 NUM(BEGIN) = NUM(SMALL)
2070 NUM(SMALL) = TEMP
2080 NEXT BEGIN
2999 RETURN
3000 FOR ROW = 1 TO N
3010 PRINT NUM(ROW)
3020 NEXT ROW
3999 RETURN
4000 DATA 8, 7, 3, 2, 1, 12, 4, 9, 11
10000 REM And the answer is ...
10010 REM 1
10020 REM 2
10030 REM 3
10040 REM 4
10050 REM 7
10060 REM 9
10070 REM 11
10080 REM 12