Translated using translate google. The original language is Russian. Original page https://hi-aga.ru/index.php/homepage/for-31-40

Example thirty-one.

: FOR31 ( N>0 -> )  \ выводим A1 A2 ... AN
2E               \ A0=2
0                \ N –> N 0 , пределы цикла
DO
    1E FSWAP F/  \ A0 -> 1/A0
    2E F+        \ 1/A0 -> 1/A0+2
    FDUP F.      \ вывод копию 2+1/A0
LOOP FDROP ;     \ сбрасываем последний «2+1/A0», очищаем стек после себя
\ Результат работы программы (при N=10):
10 FOR31
2.5000000 2.4000000 2.4166667 2.4137931 2.4142857 2.4142012 2.4142157 2.4142132 2.4142136 2.4142136  Ok

Example thirty-two.

: FOR32 ( N>0 -> )  \ выводим последовательность чисел A1 A2 ... AN
1E                \ A0=1
1+ 1              \ N –> N 0 , пределы цикла
DO
    1E F+         \ A[k-1]+1
    I S>D D>F F/  \ (A[k-1]+1)/I , «I – это k в нашем случае»
    FDUP F.       \ вывод копию (A[k-1]+1)/I
LOOP FDROP ;
\ Пример работы слова (при N=10):
10 FOR32
2.0000000 1.5000000 0.8333333 0.4583333 0.2916666 0.2152777 0.1736111 0.1467013 0.1274112 0.1127411  Ok

Example thirty-three.

: FOR33 ( N>1 -> )  \ вывести F1, F2, ... FN, если F1=1, F2=1, FK=F[K-2]+F[K-1]
DUP 3 <                    \ N –> N N<3
IF DROP 1 . 1 . EXIT THEN  \ Если «N<3», то печатаем «1 1» и выходим
1 . 1 .                    \ печатаем первые два элемента «1 1»
1 1 ROT                    \ N -> 1 1 N , иначе считаем FN
1+ 3                       \ 1 1 N -> 1 1 N+1 3 – готовим пределы цикла
DO                         \ 1 1 N+1 3 -> 1 1
    2DUP +                 \ 1 1 -> 1 1 1+1 , из предыдущих двух получаем очередной элемент
    ROT DROP               \ F[K-2] F[K-1] F[K] -> F[K-1] F[K] , удаляем элемент F[K-2]
    DUP .                  \ вывод копию F[K]
LOOP DROP DROP ;

 

Let's check for the first twenty Fibonacci numbers (we can see that this function is growing quite quickly, be careful with overflow when calculating a large number of terms of the series, so the 46th element is equal to “1836311903”, and the 47th will be negative due to overflow if operations can be rewritten to work with positive numbers, we won’t get further than the 48th element, you can rewrite them with operations for double precision numbers if necessary, but they can also be “overcome” if you really want to, a computer is just a computing machine, not a “magic device” "):
20 FOR33
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765  Ok
Example thirty-four. Identical to the previous one (differing only in the formula), we obtain from it with minor changes and replacing operations for integer numbers with real ones (due to division in the formula for AK).
: FOR34 ( N>1 -> )  \ вывести A1=1 A2=2 ... AK={A[K-2]+2*A[K-1]}/3 ... AN
DUP 3 <                    \ N –> N N<3
IF DROP 1 . 2 . EXIT THEN  \ Если «N<3», то печатаем «1 2» и выходим
1 . 2 .                    \ иначе считаем FN, печатаем первые два элемента «1 2»
1E 2E                      \ F: -> 1 2 , первые два элемента
1+ 3                       \ N -> N+1 3 – готовим пределы цикла
DO                         \ N+1 3 ->
    FDUP 2E F*             \ F: 1 2 -> A[K-2] A[K-1] A[K-1]*2
    FROT F+ 3E F/          \ A[K-2] A[K-1] A[K-1]*2 -> A[K-1] (A[K-1]*2+A[K-2])/3
    FDUP F.                \ вывод копию (A[K-1]*2+A[K-2])/3
LOOP FDROP FDROP ;
As a result of the above code, we get the following series of numbers:
10 FOR34
1 2 1.6666667 1.7777778 1.7407407 1.7530864 1.7489712 1.7503429 1.7498857 1.7500381  Ok
Example thirty-five. Here the next term is counted not through two, but three previous ones. In general, it differs little from previous examples. In the second line we compare N with four (instead of three), if less we print the first three elements and exit (I decided not to bother too much). Otherwise, in the fourth we print the first three elements and calculate the rest further. In the fifth we enter the first three terms to calculate the next one. In the sixth, we prepare the parameters of the cycle, followed by the cycle itself. Everything in the loop should be familiar, duplicate the top two elements and add them. Since it’s difficult to work with four elements (we didn’t want to resort to variables), we send this intermediate result to the return stack (the word “>R”), then move element A[K-3] to the top and multiply it by “-2 ", then we return the intermediate value of the sum from the return stack and calculate the final result (thus, we got rid of the A[K-3] element in one go, as it was not necessary). The rest is standard - we copy the last calculated element and display it on the screen, and after the cycle we clear the stack of three elements. The only innovation is working with the return stack. It must be handled especially carefully if you put something there (or remove it) and call another word, or use any construction that changes the order of execution of the program (may depend on the implementation of the compiler/interpreter, depending on where the loop data, conditional statements, etc. are stored etc., any change in the number of elements on the return stack or change in their values ​​is predictably dangerous “for the health of programs”, it is better not to risk it), then the program is guaranteed to crash with an error. The return stack serves to organize a hierarchy of subroutine calls and switching between programs and is implemented at the hardware level (at least in the x86 architecture).
: FOR35 ( N>2 -> )  \ вывести F1, F2, ... FN, если F1=1, F2=2, F3=3, AK=A[K-1]+A[K-2]-2*A[K-3]
DUP 4 <                        \ N –> N N<3
IF DROP 1 . 2 . 3 . EXIT THEN  \ Если «N<3», то печатаем «1 2 3» и выходим
1 . 2 . 3 .                    \ печатаем первые три элемента «1 2 3»
1 2 ROT 3 SWAP                 \ N -> 1 2 3 N , иначе считаем FN
1+ 4                           \ 1 2 3 N -> 1 2 3 N+1 3 – готовим пределы цикла
DO                             \ 1 2 3 N+1 3  -> 1 2 3
    2DUP +                     \ 1 2 3 -> 1 2 3 2+3
    >R                         \ 1 2 3 2+3 -> 1 2 3
    ROT -2 *                   \ 1 2 3 -> 2 3 1*(-2)
    R>                         \ 2 3 1 -> 2 3 1*(-2) 2+3
    +                          \ 2 3 1*(-2) 2+3 -> 2 3 1*(-2)+2+3
    DUP .                      \ вывод копию (A[K-1]+A[K-2]-2*A[K-3])/3
LOOP DROP DROP DROP ;
\ Проверим при N=20:
20 FOR35
1 2 3 3 2 -1 -5 -10 -13 -13 -6 7 27 46 59 51 18 -49 -133 -218  Ok
Example thirty-six. Not a particularly difficult task with nested loops, requiring a little more care, and the main thing is not to forget about the need to leave data for the limits of the nested loop parameter each time. Lines two, three, and four prepare the outer loop limits and push zero (the initial value of the series total) onto the real stack. Next comes the preparation for the nested loop, the seventh line, and in the sixth line we send N to the real stack, equal to the current value of the iteration (the member of the series that needs to be raised to a power) and one as the initial value of the power of N, and then the loop itself, which raises to the power repeated multiplication. Then we reset N and sum the two remaining numbers at the top of the stack, obtaining the current sum of the series. After the outer loop we print the final result with the word “G.” (for correct display of the exponent) and delete the input parameter “K” remaining on the integer stack.
: FOR36 ( N>0 K>0 -> )  \ вычислить 1^K+2^K+...+N^K
SWAP                \ N K -> K N
1+ 1                \ K N -> K N+1 1, прогоняю сперва все N
0E                  \ F: -> 0, заносим в вещественный стек ноль – начальное значение суммы ряда
DO                  \ K N+1 1-> K
    I S>D D>F 1E    \ F: 0 -> 0 N 1, добавили «1» –начальное значение произведения «N^K»
    DUP 1+ 1        \ K -> K K+1 1
    DO              \ K K 1 -> K
        FOVER F*    \ F: 0 N 1 -> 0 N 1*N
    LOOP
    FSWAP FDROP F+  \ F: 0 N 1*N -> 0+N^K
LOOP G. DROP ;
\ Примеры вычисления суммы квадратов от 1 до 5, 6, 7 и до 10 в 10-ой степени (для проверки правильности вывода экспоненты):
5 2 FOR36
55.000000  Ok
6 2 FOR36
91.000000  Ok
7 2 FOR36
140.00000  Ok
10 10 FOR36
1.4914342e10  Ok
This example can be rewritten without the nested loop. Fort has a built-in facility for exponentiation in one operation. I’ll just give an example of exponentiation; if you wish, modify the above code yourself, because the example should show the use of a loop in a loop, and not skill and knowledge. Example 5 to the power of 5:
5E 5E F** F.
3125.0000  Ok
Example thirty-seven. A modification of the previous one, in which the limit of the inner loop parameter "K" is replaced by the current value of the outer loop parameter. In general, a minimum of edits and the problem is solved.
: FOR37 ( N>0 -> )  \ вычислить 1^1+2^2+...+N^N
1+ 1                \ I: N -> N+1 1, прогоняю все N
0E                  \ F: -> 0, заносим в вещественный стек ноль – начальное значение суммы ряда
DO                  \ I: N+1 1->
    I DUP           \ I: I I, (I=N)
    S>D D>F 1E      \ F: 0 -> 0 N 1, «1» – это начальное значение произведения «N^N»
    1+ 1            \ I: I -> I+1 1
    DO              \ I: I+1 1 ->
        FOVER F*    \ F: 0 N 1 -> 0 N 1*N
    LOOP
    FSWAP FDROP F+  \ F: 0 N 1*N -> 0+N^N
LOOP G. ;
\ Тесты:
1 FOR37
1.0000000  Ok
2 FOR37
5.0000000  Ok
3 FOR37
32.000000  Ok
4 FOR37
288.00000  Ok
5 FOR37
3413.0000  Ok
Example thirty-eight. To run the degrees in reverse order, we additionally copy the input parameter “N”, and from it we calculate “N-I+1” (for example, for “N=5”, “I=1” – “N-I+1 =5-1+1=5", "I=2" - "N-I+1=5-2+1=4 ... and "I=5" - "N-I+1=5-5+1 =1, thus obtaining a countdown for the nested loop parameter). Otherwise everything is the same as in the previous examples.
: FOR38 ( N>0 -> )  \ вычислить 1^N+2^(N-1)+...+N^1
DUP 1+ 1            \ I: N -> N N+1 1, прогоняю все N
0E                  \ F: -> 0, заносим в вещественный стек ноль – начальное значение суммы ряда
DO                  \ I: N N+1 1-> N
    I DUP           \ I: N -> N I I, (I=N)
    S>D D>F 1E      \ F: 0 -> 0 N 1, «1» – это начальное значение произведения «N^N»
    OVER SWAP –     \ I: N I  -> N N-I
    1+ 1 SWAP       \ I: N N-I -> N 1 N-I+1
    DO              \ I: N 1 N-I+1 -> N
        FOVER F*    \ F: 0 N 1 -> 0 N 1*N
        -1
    +LOOP
    FSWAP FDROP F+  \ F: 0 N 1*N -> 0+N^N
LOOP G. DROP ;
\ Тесты дают следующие результаты:
1 FOR38
1.0000000  Ok
2 FOR38
3.0000000  Ok
3 FOR38
8.0000000  Ok
4 FOR38
22.000000  Ok
5 FOR38
65.000000  Ok
Example thirty-nine. The simplest example after the previous ones. In the outer loop, we run I from A to B, and in the inner loop, we print the current value of the parameter a number of times equal to its value.
: FOR39 ( A>0 B>0 -> )  \ A (A раз) A+1 (A+1 раз)… A+N (A+N раз) {A<B}
1+ SWAP ( B+1 A )  \ A B -> B+1 A
DO                 \ B+1 A ->
    I DUP 0        \ -> I I 0, от нуля до (I-1), то есть «I» раз повторяем вложенный цикл
    DO             \ I I 0 -> I
        DUP .      \ печатаем I (I= от A до B) I раз
    LOOP
    DROP           \ удаляем I за ненадобностью, оставляем стек чистым после себя
LOOP ;
\ Тест:
2 7 FOR39
2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7  Ok
Example forty. In line two, I push one onto the stack - the initial value of the number of repetitions and the limits of the loop parameter. From the third to the ninth outer cycle. The fourth is the limits of the parameter of the inner loop, and from the fifth to the seventh lines of the nested loop, inside which we duplicate “I” and print it (the current value of the outer loop parameter), after which “I” is reset and the number of repetitions of the output of the current number is increased by one after which goes “CR” - just for the beauty of the output and the convenience of counting the number of repetitions when checking the results.
: FOR40 ( A>0 B>0 -> )  \ A (1 раз) A+1 (2 раз)… A+N (N раз) {A<B}
1+ SWAP 1 ROT ROT  \ A B -> 1 B+1 A, пределы цикла, а один - начало числа повторений
DO                 \ 1 B+1 A ->1
    I OVER 0       \ 1 -> 1 I 1 0
    DO             \ 1 I 1 0 -> 1 I
        DUP .      \ печатаю «I» … раз
    LOOP
    DROP 1+ CR     \ 1 I -> 1+1, сбрасываю «I» и увеличиваю число повторений
LOOP DROP ;        \ сбрасываю число повторений
\ По традиции тест:
1 10 FOR40
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10
 Ok