Q(uick)BASIC Statement: SWAP
Quick View
SWAP
An assignment statement that exchanges the values of two variables
Worth knowing
Useful and cross-version information about the programming environments of QBasic and QuickBasic.
Syntax
- SWAP variable1, variable2
Description/Parameter(s)
variable1 and variable2 | Two variables of the same data type. |
Example
a% = 1: b% = 2
PRINT "Before: "; a%, b%
SWAP a%, b%
PRINT "After: "; a%, b%
Syntax
- SWAP variable1,variable2
Description/Parameter(s)
Any type of variable can be swapped (integer, long, single precision, double precision, string, or record). However, the two variables must be exactly the same type or an error message appears ("Type mismatch"). For example, trying to swap an integer with a single-precision value produces a "Type mismatch" error.
Examples
The following program sorts the elements of a string array in descending order using a Shell sort. It uses SWAP to exchange array elements that are out of order.
' Sort the word list using a Shell sort.
Num% = 4
Array$(1) = "New York"
Array$(2) = "Boston"
Array$(3) = "Chicago"
Array$(4) = "Seattle"
Span% = Num% \ 2
DO WHILE Span% > 0
FOR I% = Span% TO Num% - 1
J% = I% - Span% + 1
FOR J% = (I% - Span% + 1) TO 1 STEP -Span%
IF Array$(J%) <= Array$(J% + Span%) THEN EXIT FOR
'
' Swap array elements that are out of order.
'
SWAP Array$(J%), Array$(J% + Span%)
NEXT J%
NEXT I%
Span% = Span% \ 2
LOOP
CLS
FOR I% = 1 TO Num%
PRINT Array$(I%)
NEXT I%
END
This program could be converted into a useful SUB, which would sort a string array of any size, by using the SUB...END SUB statements as shown below:
' Sort the word list using a Shell sort.
SUB ShellSort (Array$(), Num%) STATIC
Span% = Num% \ 2
DO WHILE Span% > 0
FOR I% = Span% TO Num% - 1
J% = I% - Span% + 1
FOR J% = (I% - Span% + 1) TO 1 STEP -Span%
IF Array$(J%) <= Array$(J% + Span%) THEN EXIT FOR
' Swap array elements that are out of order.
SWAP Array$(J%), Array$(J% + Span%)
NEXT J%
NEXT I%
Span% = Span% \ 2
LOOP
END SUB
Syntax
- SWAP variable1, variable2
Description/Parameter(s)
Usage Notes
- SWAP is an assignment statement that exchanges the values of two variables.
- Any type of variable can be swapped (integer, long, single precision, double precision, string, currency, or record). However, if the two variables are not exactly the same type, BASIC generates the error message, "Type mismatch."
Example
This example uses the SWAP statement to exchange array elements that are out of order. The program sorts a string array in descending order using a shell sort.
Num% = 4
Array$(1) = "New York"
Array$(2) = "Boston"
Array$(3) = "Chicago"
Array$(4) = "Seattle"
Span% = Num% \ 2
DO WHILE Span% > 0
FOR I% = Span% TO Num% - 1
J% = I% - Span% + 1
FOR J% = (I% - Span% + 1) TO 1 STEP -Span%
IF Array$(J%) <= Array$(J% + Span%) THEN EXIT FOR
' Swap array elements that are out of order.
SWAP Array$(J%), Array$(J% + Span%)
NEXT J%
NEXT I%
Span% = Span% \ 2
LOOP
CLS
FOR I% = 1 TO Num%
PRINT Array$(I%)
NEXT I%
END