News:

Building a 3D Ray Tracer  By stevmjon

Main Menu

Learn To Code: Swap Integers Custom Function

Started by kevin, August 15, 2022, 08:23:03 PM

Previous topic - Next topic

kevin

    Learn To Code: Swap Integers Custom Function

     There's any number of ways to SWAP (exchange) the contents of two integers variables, Normally I would copy one of the variables into a third TEMP variable then proceed to copy the values around, but you can do it without the added temp variable also.  

     Here's a method that just uses additions and subtractions

PlayBASIC Code: [Select]
      // Declare our two pair of variable for our swap test
a=-100
b=50

// Display the current values in both A and B variables
print "Original Values:"
print "A="+Str$(A)
print "B="+Str$(A)
print ""


// Call our SWAP INTEGERS Function
A,B=SwapInts(A,B)


// Display the new values in both A and B variables
print "Value After Swap"
print "A="+Str$(A)
print "B="+Str$(A)
print ""


// Show the graphics screen to the user and wait for a KEY
// before ENDING
Sync
waitkey
END



// -------------------------------------------------
// Swap Integers Function
// -------------------------------------------------

Function SwapInts(X,Y)

// store the sum of both input values in X
X=X+Y

// To compute NEW Y we subtract OLD Y from the X+Y sum
Y=X-Y

// To compute NEW X we subtract SWAPPED Y from the X+Y sum
X=X-Y

// restore this pair of values back to the caller
EndFunction X,Y





   Note: PlayBASIC has a built in SWAP function