THE PUZZLET PAGE

 FUNCTION:  ReverseString().  This function takes an string as its argument and returns the reverse of that string to the calling routine. If its argument is, say, "123456" it will return "654321".

 Declaring the function must be done like this: declare ReverseString(str1\$: string) Here's the code: sub ReverseString(str1\$) ' returns the reverse of string str1\$ ' example: str1\$ = "knob" returns "bonk" def i, L: int def rev\$: string L = len(str1\$) rev\$ = "" for i = L to 1 #-1     rev\$ = rev\$ + mid\$(str1\$, i, 1) next i return rev\$

 Variable i is used to iterate over the individual characters of argument str1\$. Variable L holds the length of argument nstr1\$. Variable n\$ holds the string version of n. Variable rev\$ is used to build up the reverse of str1\$. I've numbered the important lines of code to assist in a detailed explanation, as shown below.

 123456 L = len(str1\$) rev\$ = "" for i = L to 1 #-1     rev\$ = rev\$ + mid\$(str1\$, i, 1) next i return rev\$

 Now for a line-by-line exegesis of the code.

 1 L = len(str1\$).  Uses built-in function  len() to work out the number of characters in str1\$, storing the result in variable L.

 2 rev\$ = "".  We're going to use variable rev\$ (short for "reversed string") to build up and hold the reversal we need. This line initialises it as an empty string, that is, one containing no characters at all.

 3 for i = L to 1 #-1.  The most important task can now begin. We have to iterate over the whole of str1\$, working on one character at a time. This line uses i as iterator, or control. It starts at value L and reduces to value 1, going one decremental step at a time.

4

rev\$ = rev\$ + mid\$(str1\$, i, 1).  A paraphrase of this line is "take one character from within str1\$ at position i and add it on to the end of whatever is in rev\$ at this time."

Let's take the example where n\$ equals "24358". At the beginning of the FOR-NEXT loop, rev\$ holds "" (empty string) and i equals 5 (because i initially equals L, and L equals the length of n\$). As i iterates down towards 1, rev\$ is built up with its characters in reverse to n\$. This is shown clearly in the table:

 Value of i Contents of rev\$ Initial "" 5 "8" 4 "85" 3 "853" 2 "8534" 1 "85342"

 5 next i.  Instructs the FOR-NEXT loop to go around again until i has covered the required range.

 6 return rev\$.  The transformation is complete, and all that remains to be done is to return the result to the calling routine.

 Note: this function works perfectly well for non-numeric characters.

 MAIN MENU HOW DOES IT WORK?

 Site design/maintenance: Dave Ellis E-mail me! Last Updated: February 5th, 2010.