A long time ago, I saw an article on csdn about object-oriented implementation in C, which is classic, but I was not able to understand the article yet. However, it still gives me a lot of inspiration-real masters should not be restricted by a language! A master can implement classes in C, and should also implement recursion in basic ---- (I'm boasting about myself ). This program runs in gvbasic. This is a programming language I first learned-I taught QBASIC in school before, but unfortunately I didn't study it seriously-then I suddenly became interested in writing programs on wenquxing, take out the qBASIC book and read it ~~~
Later, I used gvbasic to write a game on wenquxing. At that time, I felt that a good syntax in a language can determine the difficulty of writing a program. This is for beginners and experts, these do not exist ~~~ After I learned C and used gvbasic on wenquxing, I found that I started to follow Structured Programming and it made me very easy!
For recursion, I have always replaced it with a loop-maybe because I started with basic, so I don't like recursion very much. But when I access more and more algorithms, I find that recursion is so important!
So I used the stack data structure and the function calling principle in C to implement simulated recursion in basic! This process took me an hour! In addition, there is no pointer concept in basic (no memory allocation function in gvbasic-some API functions can be used to allocate memory in VB ), the linked list cannot be used, but we can simulate it ~ --- Of course, for this example, the simulation process must be more complex!
The following code is used:
Printt "implement recursion in basic"
Printt "an example of factorial"
Print "Kevin Lynx 2006.1.3"
Rem int getn (int n)
Rem {
Rem if (n = 1) return 1;
Rem return N * getn (n-1 );
Rem}
P =-1
Size = 255
Dime S (size)
Go 250
Rem push stack sub
P = p + 1
If P> 254 then print "stack overflow": End
S (p) = Param
Return
Rem pop stack sub
If P <0 then 230
Param = s (P)
P-1 =
230:
Return
250:
Print "enter a positive integer ";
Input ""; n
If n <1 then 250
Gousb 310
Go 440
300:
Rem getn
310:
If n = 1 then 390
Rem before call itself, push stack first
Param = N
Gosub 140
REM and now can call itself
N = N-1
Gosub 310
Rem pop stack now
Gosub 200
N = N * Param
Param = 1
Rem return now
Return
440:
Print "result ="; n