Игры на JS

JavaScript (JS) — один из самых популярных языков программирования для создания веб-приложений, включая игры. Вот несколько примеров игр, которые можно создать на JavaScript:

Игра Камень, ножницы, бумага

Камень-ножницы-бумага: классическая детская игра, в которой участники одновременно выбирают один из трех символов - камень, ножницы или бумагу. Победитель определяется по правилам: камень побеждает ножницы, ножницы побеждают бумагу, бумага побеждает камень.

поиграть

Игра Кено

Кено: лотерейная игра, в которой игрок выбирает набор чисел из общего диапазона. Затем производится случайное извлечение чисел, и игрок получают выигрыш в зависимости от совпадения чисел на своей карте с выигрышными номерами.

поиграть

Игра Кости

Кости: игра, в которой бросается кубик (кубики) с числами. В зависимости от выпавшего значения, игроки могут делать ставки на различные исходы (результаты) бросков.

поиграть

Игра Монетка (орел или решка)

Монетка - это игра, в которой бросают монету и делают ставки на то, какой стороной она упадет - орел или решка. Просто нажмите на картинку Орла или Решки, затем на кнопку "Выбрать".

поиграть

Игра Слот-машина

Нажмите кнопку "Испытать судьбу", чтобы получить символы в случайном порядке. Игрок выигрывает, если выпадает три одинаковые фигуры

поиграть

Игра Виселица

Знакомая всем с детства игра. Просто угадывайте буквы, чтобы разгадать слово. В данном исполнении игра стала похожа на "Поле чудес".

поиграть

Игра Угадайка

Знакомая с детства игра. Просто введите число от 1 до 100. Решите математическую задачу: за какое максимальное количество ходов гарантированно можно угадать число.

поиграть

Игра Питон

Игра "Питон" ("Змейка") - это цифровое воплощение простоты и увлекательности. В ней игрок управляет змеей, которая ползет по пиксельному миру в поисках яблок и других фруктов и овощей. С каждым съеденным фруктом змея удлиняется, а игра ускоряется. Это испытание ловкости, стратегии и терпения, где каждое движение может привести к новому рекорду или неожиданному концу. Змея скользит между препятствиями, создавая узоры на экране, напоминающие танец в бесконечном лабиринте. Эта игра - отражение эры ретро-игр, где простые концепции превращаются в часы захватывающего геймплея.

поиграть

Библиотеки и движки для создания игр на JS:

  • Phaser.js: Популярный игровой фреймворк для 2D-игр. Предлагает множество инструментов для создания игр, начиная от управления анимацией и физикой, заканчивая аудио поддержкой и управлением пользователем.
  • Three.js: Используется для создания 3D-графики в браузере, включая сложные игры с трёхмерными мирами.
  • Babylon.js: Еще один мощный фреймворк для разработки 3D-игр и приложений в браузере.
  • p5.js: Библиотека, подходящая для создания интерактивных графических приложений, включая игры.

Шахматы 

Шахматы — это настольная стратегическая игра, которая играется на квадратной доске размером 8x8 клеток. В игре участвуют два игрока, каждый из которых управляет армией из 16 фигур: 1 король, 1 ферзь, 2 ладьи, 2 слона, 2 коня и 8 пешек. Основная цель игры — поставить мат королю противника, то есть создать такую позицию, при которой король соперника не может избежать взятия.

Основные правила и фигуры:

  1. Фигуры и их ходы:

    • Король: Ходит на одну клетку в любом направлении.
    • Ферзь: Ходит на любое количество клеток по горизонтали, вертикали или диагонали.
    • Ладья: Ходит на любое количество клеток по горизонтали или вертикали.
    • Слон: Ходит на любое количество клеток по диагонали.
    • Конь: Ходит буквой "Г" — две клетки в одном направлении и одна в перпендикулярном. Конь — единственная фигура, которая может перепрыгивать через другие фигуры.
    • Пешка: Ходит на одну клетку вперед, но бьет на одну клетку по диагонали. На первом ходе может сделать два шага вперед. Если пешка достигает последнего ряда (8-го или 1-го), она может быть превращена в любую другую фигуру (чаще всего в ферзя).
  2. Цель игры:

    • Шах: Это ситуация, когда король находится под угрозой взятия. Игрок должен устранить угрозу, иначе он проиграет.
    • Шах и мат: Это ситуация, при которой король находится под шахом и не может избежать взятия в следующий ход. Это завершает игру, и игрок, поставивший мат, побеждает.
    • Пат: Это ситуация, при которой игрок, чей ход, не может сделать ни одного допустимого хода, но при этом его король не находится под шахом. Пат приводит к ничьей.
  3. Дополнительные правила:

    • Рокировка: Специальный ход, при котором король и ладья перемещаются одновременно. Король перемещается на две клетки в сторону ладьи, а ладья ставится на клетку, через которую король перепрыгнул. Рокировка возможна только при выполнении определенных условий (например, король и ладья еще не ходили, между ними нет других фигур, король не находится под шахом и не проходит через клетки, находящиеся под угрозой).
    • Взятие на проходе: Это специальный ход пешкой, который возможен, если пешка противника сделала два шага вперед с исходной позиции, а ваша пешка могла бы взять её, если бы она сделала один шаг. Взятие на проходе должно быть выполнено сразу же после такого хода.

Стратегия и тактика:

Шахматы требуют как стратегического планирования на протяжении всей игры, так и тактических расчетов для выигрыша отдельных фигур и позиций. Хорошие шахматисты должны уметь предсказывать ходы противника, рассчитывать возможные последствия своих действий на несколько шагов вперед и понимать общую позиционную игру.

История и культура:

Шахматы имеют долгую историю, восходящую к Индии VI века, где игра, известная как "чатуранга", была предшественником современных шахмат. Со временем шахматы распространились по всему миру, приобретая популярность в различных культурах.

Сегодня шахматы играют важную роль в культуре и спорте, с миллионами игроков по всему миру и множеством международных турниров, включая престижный матч за звание чемпиона мира. В последние годы интерес к шахматам возрос благодаря доступности онлайн-игр и популярным сериалам, таким как "Ход королевы" (The Queen's Gambit).

8 ферзей

Размещение 8 ферзей на шахматной доске размером 8 на 8 возможно 92 способами. Разумеется при условии, что ни одни из них не угрожает остальным.

Перейдя по ссылке вы увидите все эти варианты на отдельной странице.

Ферзь 8 x 8

Разместить 5 ферзей на шахматной доске размером 5 на 5 возможно 10 способами

Ферзь 5 x 5

Разместить 6 ферзей на шахматной доске размером 6 на 6 возможно 4 способами

Ферзь 6 x 6

Разместить 7 ферзей на шахматной доске размером 7 на 7 возможно 40 способами

Ферзь 7 x 7

Размещение 2, 3, 4 Ферзей на полях соответствующих размеров при аналогичном условии невозможно (тривиальный случай одного ферзя на поле 1 x 1 не рассматриваем).

Разместить 9 ферзей на шахматной доске размером 9 на 9 возможно 352 способами

Ферзь 9 x 9

Разместить 10 ферзей на шахматной доске размером 10 на 10 возможно 726 способами

Ферзь 10 x 10

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

Example twenty-one. In this problem we find the value of the exponent, a rather interesting task not only for educational purposes, but also for practical purposes, despite the fact that in Forth you can get this value simply by typing the following code:
1E FEXP F.
2.7182818  Ok
: FOR21 ( I: N>0 ->  )  \ 1/1!+1/2!+1/3!+...+1/N!
1+ 1             \ пределы параметра цикла от 1 до N
1E 1E            \ F:  -> 1 1 – первая единица – это текущая сумма ряда, вторая текущий ее член
DO
    I 0 D>F F/   \ F: S 1 –> S 1/I
    FSWAP FOVER  \ S 1/I -> 1/I S 1/I
    F+ FSWAP     \ 1/I S 1/I -> S+1/I 1/I
LOOP FDROP F. ;  \ удаляем текущий член (1/I) печатаем сумму (S+1/I)
\ Тест словом TEST-FOR21 проверим не только работу решения задачи, но и сходимость данного метода вычисления экспоненты.
: TEST-FOR21 11 1 DO I DUP . FOR21 CR LOOP ;
\ В итоге на экране получим следующий результат:
TEST-FOR21
1 2.0000000
2 2.5000000
3 2.6666667
4 2.7083333
5 2.7166667
6 2.7180556
7 2.7182540
8 2.7182788
9 2.7182815
10 2.7182818
 Ok
For N=10 we get the result accurate to seven decimal places. Example twenty two. We use the variable X, otherwise manipulations on the stack will be unreasonably complex, and there will be no clarity.
VARIABLE X
: FOR22 ( I: N>0 F: X ->  )  \ 1+X/1!+X^2/2!+X^3/3!+...+X^N/N!
X F!             \ сохраняем значение X в одноименной переменной
1+ 1             \ пределы параметра цикла от 1 до N
1E 1E            \ F:  -> 1 1 – первая единица – это текущая сумма ряда, вторая текущий ее член
DO
    X F@ F*      \ F: S 1 –> S 1*X
    I 0 D>F F/   \ F: S 1*X –> S 1*X /I
    FSWAP FOVER  \ S 1*X/I -> 1*X/I S 1*X/I
    F+ FSWAP     \ 1*X/I S 1*X/I -> S+1*X/I 1*X/I
LOOP FDROP F. ;  \ удаляем текущий член (1*X/I) печатаем сумму (S+1*X/I)
The only difference from the previous example is the addition of line one (variable X) and seven (the current member of the series in the loop is multiplied by X each time before the next summation).

Test with the word TEST-FOR22 let's check the operation of FOR22 with the parameter X=1E (a special case, we reduce the problem to the previous one, we get the same data, check it yourself).
\ Теперь проанализируем с параметром, например, два.
: TEST-FOR22 21 1 DO I DUP . 2E FOR22 CR LOOP ;
TEST-FOR22
1 3.0000000
2 5.0000000
3 6.3333333
4 7.0000000
5 7.2666667
6 7.3555556
7 7.3809524
8 7.3873016
9 7.3887125
10 7.3889947
11 7.3890460
12 7.3890546
13 7.3890559
14 7.3890561
15 7.3890561
16 7.3890561
17 7.3890561
18 7.3890561
19 7.3890561
20 7.3890561
 Ok
We see that the convergence is worse, with I=14, we get an approximate result (for some reason with rounding). Be careful with real numbers (they can be weird).

Example twenty three. The first line is the declaration of an auxiliary variable. The second standard beginning is the description of the word. Third, we set the limits of the cycle. The fourth, after triple duplication, we get: the first parameter is the initial value of the sum, the second term of the sum, the third square X is stored in a variable of the same name, we will need it to calculate the next term of the series. From the fifth to the eleventh cycle in which we calculate the term of the series and add it to the value of the sum of the series.
In the sixth we read the value of the variable X, where its square is stored, multiply by (An) and change the sign to the opposite, in the seventh loop parameter I we multiply by two, duplicate and increase by one, as a result we get (2*I) on the real stack and (2*I+1), which in the eighth we multiply by each other, and the result is a divisor for (–An*X^2) (as a result of these manipulations we obtain the factorial in the denominator). In the ninth and tenth, we add the resulting current term to the sum of the series, and return the original order. As a result, in the twelfth, we have the sum of the series and its last term ready, discarding which, if unnecessary, we print the final result.
: FOR23 ( F: X I: N>0 -> )  \ 1.5E 5 FOR23=SIN[1.5] X-X^3/3!+X^6/6!-...+[-1]^N*X^[2*N+1]/[2*N+1]!
1+ 1                         \ пределы параметра цикла
FDUP FDUP FDUP F* X F!       \ X -> X X , первый X – сумма ряда (S), второй ее член (An), X=X^2
DO
    X F@ F* FNEGATE          \ S An -> S –An*X^2
    I 2* DUP 1+ 0 D>F 0 D>F  \ S –An*X^2 -> S –An*X^2 2*I 2*I+1
    F* F/                    \ S –An*X^2 2*I 2*[I+1] -> S –An*X^2/{2*I*2*[I+1]}
    FSWAP FOVER              \ S -An*X^2/{2*N+1}! -> -An*X^2/{2*N+1}! S -An*X^2/{2*N+1}!
    F+ FSWAP                 \ -An S -An -> S-An -An
LOOP
FDROP F. ;                   \ удаляем текущий член (1*X/I) печатаем сумму ряда
Test at angles of 0, 1.5 and 3.14 (Pi) radians with a number of iterations of five. Experiment with other values ​​yourself.
0E 5 FOR23
0.0000000  Ok
1.5E 5 FOR23
0.9974949  Ok
FPI 5 FOR23
>-0.0004451  Ok
Example twenty-four. Twin brother of the previous one. We replace the first term with one (instead of X), and proceed similarly with the sum of the series. We use the previously declared variable, everything else remains unchanged. Using mathematics, it was possible not to write the word FOR24, but using reduction formulas to calculate COS through SIN, although I think the purpose of study is to gain experience in programming, and not in demonstrating knowledge in mathematics.
: FOR24 ( F: X I: N>0 -> )  \ 1.5E 5 FOR23=COS[1.5] 1-X^2/2!+X^4/4!-...+[-1]^N*X^[2*N]/[2*N]!
1+ 1                         \ пределы параметра цикла
FDUP F* X F! 1E 1E           \ X -> 1 1 , первый 1 – сумма ряда (S), второй ее член (An), X=X^2
DO
    X F@ F* FNEGATE          \ S An -> S –An*X^2
    I 2* DUP 1- 0 D>F 0 D>F  \ S –An*X^2 -> S –An*X^2 2*I 2*I-1
    F* F/                    \ S –An*X^2 2*I 2*I-1 -> S –An*X^2/{2*I*[2*I-1]}
    FSWAP FOVER              \ S -An*X^2/{2*I}! -> -An*X^2/{2*I}! S -An*X^2/{2*I}!
    F+ FSWAP                 \ -An S -An -> S-An -An
LOOP
FDROP F. ;                   \ удаляем текущий член (1*X/I) печатаем сумму ряда
\ Тесты на вычисление косинуса углов 0, 3,14 (Пи) и 1,5 радиан, для параметра итерации равной пяти.
0E 5 FOR24
1.0000000  Ok
FPI 5 FOR24
-1.0018291  Ok
FPI 10 FOR24
-1.0000000  Ok
1.5E 5 FOR24
0.0707369  Ok
Example twenty-five. The second line is storing the input parameter in a variable of the same name. In the third, we add zero (the initial value of the sum) and minus one (the initial value of the workpiece for calculating the “n” term) to the real stack. The fourth we prepare the cycle and from the fifth to the ninth the cycle itself, in which we read “X”, multiply it by the workpiece and change the sign to the opposite (for this we first made it minus one in order to get the first term positive, as in the problem statement). Next, we duplicate and calculate the member of the series itself, dividing by “I” (the loop iteration parameter), adding to the previous sum, and restoring the original order of the parameters. All this is so as not to spoil the preparation for calculating the next element of the series, because it will not be easy to calculate the next one using the previous one.
: FOR25 ( |X|<1 N>0 -> )  \ 0.5E 5 FOR25 = ln[1+X] , X-X^2/2+X^3/3-...+[-1]^[N-1]*X^N/N
X F!                 \ сохраняем значение X в переменную
0E -1E               \ 0 – сумма, -1 – первый член
1+ 1                 \ пределы цикла
DO
    X F@ F* FNEGATE  \ S An -> S -An*X
    FDUP I 0 D>F F/  \ S -An*X -> S -An*X -An*X/I
    FROT F+ FSWAP    \ S -An*X -An*X/I -> S-An*X/I -An*X
LOOP FDROP F. ;      \ удаляем текущий член печатаем сумму ряда
Парочка тестов:
0.1E 10 FOR25
0.0953101  Ok
0.2E 10 FOR25
0.1823215  Ok
0.3E 10 FOR25
0.2623641  Ok              
\ А теперь проверим вычислив данные значения стандартными средствами Форта.
1.1E FLN F.
0.0953101  Ok
1.2E FLN F.
0.1823215  Ok
1.3E FLN F.
0.2623642  Ok
If someone doesn’t like the difference in the last digit when calculating “0.3E 10 FOR25”, then you can increase the number of elements of the series so that with N=20 we get the same result. Experiment yourself on different data to see how quickly the series converges (and what value of N is sufficient in different cases).
Example twenty-six. The series converges very quickly. In line two, the first two “FDUP” give the initial value of the sum and the blank for the “n”th member of the series, which is obtained by multiplying by the square of “X” stored in the variable of the same name, and dividing by (2*I+1), the next two “ FDUP" allows you to get the square of "X" after multiplication. Everything else is standard, as before, preparing the limits of the cycle parameter and the cycle itself, in which we multiply the blank of the “n”-th term by the square “X”, duplicate and divide by (2*I+1), obtaining directly the term of the series ( since the next one cannot be obtained from the previous term, due to the fact that the denominators have different numbers), then we add the sum to the previous value and return the original order of the parameters on the stack.
: FOR26 ( |X|<1 N>0 -> )  \ 0.5E 5 FOR25 = ln[1+X] , X-X^3/3+X^5/5-...+[-1]^N*X^(2*N+1)/ (2*N+1)
FDUP FDUP FDUP F* X F!     \ X -> X X , 1-ый X сумма, второй - первый член, X=X^2
1+ 1                       \ пределы цикла
DO
    X F@ F* FNEGATE        \ S An -> S -An*X^2
    FDUP I 2* 1+ 0 D>F F/  \ S -An*X^2-> S -An*X^2 -An*X^2/(2*I+1)
    FROT F+ FSWAP          \ S -An*X^2 -An*X^2/(2*I+1) -> -An*X^2/(2*I+1)+S -An*X^2
LOOP FDROP F. ;            \ удаляем текущий член печатаем сумму ряда
\ Напоследок парочка тестов примера 26:
0.1E 5 FOR26
0.0996686  Ok
0.2E 5 FOR26
0.1973955  Ok
0.3E 5 FOR26
0.2914567  Ok
Of course, these values ​​can be calculated directly by one operation (the corresponding built-in function) of the Forth language. This is how we will check the correctness of the written word.
0.1E FATAN F.
0.0996686  Ok
0.2E FATAN F.
0.1973955  Ok
0.3E FATAN F.
0.2914567  Ok
Example twenty-seven. In the third line, we prepare the initial value of the sum of the series and the blank for the first member; we also wrote the value of its square in the variable “X”, since each member of the series is greater than the previous one by this number, we use it. Next comes the standard cycle with setting its limits. In the body of the loop, we multiply the blank for each element of the row by “X^2” (sixth line), by “2*I-1” (seventh line), divide by “2*I” (eighth line), duplicate and divide by “ 2*I+1" (ninth line), since this action is different for each member, we do not change the blank (so as not to “spoil” it), then, as before, we add it with the current amount and restore the order of the parameters on the stack. The eleventh line displays the current values ​​of the element of the series and its sum, so you can see how quickly the series converges (if you get tired of playing around, you can delete it).
: FOR27 ( |X|<1 N>0 -> )  \ 0.5E 5 FOR25
\ arcsin[X]=X+1*X^3/(2*3)+1*3*X^5/(2*4*5)+...+1*3*…*(2*N-1)*X^(2*N+1)/ (2*4*…*(2*N)*(2*N+1))
FDUP FDUP FDUP F* X F!  \ X -> X X , 1-ый X сумма, 2-ой – заготовка первого члена
1+ 1                    \ пределы цикла
DO
    X F@ F*             \ S An -> S An*X^2
    I 2* 1- 0 D>F F*    \ S An*X^2 -> S An*X^2*(2*I-1)
    I 2* 0 D>F F/ FDUP  \ S An*X^2*(2*I-1) -> S An*X^2*(2*I-1)/(2*I) An*X^2*(2*I-1)/(2*I)
    I 2* 1+ 0 D>F F/    \ -> S An*X^2*(2*I-1)/(2*I) An*X^2*(2*I-1)/(2*I*{2*I+1})
    FROT F+ FSWAP       \ -> An*X^2*(2*I-1)/(2*I*{2*I+1})+S An*X^2*(2*I-1)/(2*I)
FDUP F. FOVER F. CR     \ выводим текущие значения «An» и суммы
LOOP FDROP F. ;         \ удаляем текущий член печатаем сумму ряда
\ Для «Пи/4» мы получим следующее:
FPI 4E F/ 30 FOR27
0.2422365 0.8661436
0.1120677 0.8885572
0.0576075 0.8967868
0.0310933 0.9002416
0.0172619 0.9018109
0.0097606 0.9025617
0.0055908 0.9029345
0.0032331 0.9031246
0.0018835 0.9032238
0.0011037 0.9032763
0.0006499 0.9033046
0.0003842 0.9033200
0.0002278 0.9033284
0.0001355 0.9033331
0.0000808 0.9033357
0.0000482 0.9033371
0.0000289 0.9033380
0.0000173 0.9033384
0.0000104 0.9033387
0.0000062 0.9033389
0.0000037 0.9033389
0.0000022 0.9033390
0.0000013 0.9033390
0.0000008 0.9033390
0.0000005 0.9033391
0.0000003 0.9033391
0.0000001 0.9033391
0.0000001 0.9033391
0.0000000 0.9033391
0.0000000 0.9033391
0.9033391  Ok
After a little research, we can easily determine where the next element of the sum becomes zero and does not affect the further sum. Now let's calculate several arcsin values ​​for the following angles:
0.1E 30 FOR27
0.1001674  Ok
0.2E 30 FOR27
0.2013579  Ok
0.3E 30 FOR27
0.3046926  Ok
Let's calculate the same values ​​using standard Forth tools and prove the correctness of our (easy to write) word:
0.1E FASIN F.
0.1001674  Ok
0.2E FASIN F.
0.2013579  Ok
0.3E FASIN F.
0.3046926  Ok
Example twenty-eight. In the third line we save X, enter two units as the sum and the first term. Next is the already familiar cycle. Each time we multiply a member of the series by “X” and alternately change the sign to the opposite one, multiply by “2*I-3” and divide by “2*I”. We restore order after receiving the current amount. The eleventh line contains commented out code that displayed the current values ​​of the sum and element of the series in a loop (you can see for yourself how poorly the series converges and how many iterations are needed for acceptable accuracy when X approaches one). It is usually not recommended to comment on code; some programmers may consider it bad manners, but during debugging it is a very convenient trick (turning individual functions on and off).
: FOR28 ( |X|<1 N>0 -> )  \ 1E 10 FOR28
\ SQRT[1+X]=1+X/2-1*X^2/(2*4)+1*3*X^3/(2*4*6)-...+(-1)^(N-1)1*3*…*(2*N-3)*X^(N)/ (2*4*…*(2*N))
X F! 1E 1E               \ X -> 1 1 , 1-ый сумма, 2-ой – заготовка первого члена
1+ 1                     \ пределы цикла
DO
    X F@ F* FNEGATE      \ S An -> S -An*X
    I 2* 3 – S>D D>F F*  \ S -An*X -> S -An*X*(2*I-3)
    I 2* S>D D>F F/      \ S -An*X*(2*I-3) -> S -An*X*(2*I-3)/(2*I)
    FSWAP FOVER          \ S -An*X*(2*I-3)/(2*I) -> -An*X*(2*I-3)/(2*I) S -An*X*(2*I-3)/(2*I)
    F+ FSWAP             \ -> S-An*X*(2*I-3)/(2*I) -An*X*(2*I-3)/(2*I)
\ FDUP F. FOVER F. CR    \ выводим текущие значения «An» и суммы
LOOP FDROP F. ;          \ удаляем текущий член печатаем сумму ряда
\ Стандартные тесты для корней из 1,1; 1,2; 1,5; 1,9 – чем ближе к единице, тем хуже точность при одних и тех же количествах итераций:
0.1E 10 FOR28
1.0488088  Ok
0.2E 10 FOR28
1.0954451  Ok
0.5E 10 FOR28
1.2247421  Ok
0.9E 10 FOR28
1.3769956  Ok
\ Те же корни, полученные стандартными средствами Форт:
1.1E FSQRT F.
1.0488088  Ok
1.2E FSQRT F.
1.0954451  Ok
1.5E FSQRT F.
1.2247449  Ok
1.9E FSQRT F.
1.3784049  Ok
\ Для корня из двух получаем следующие данные:
2E FSQRT F.
1.4142136  Ok
1E 10 FOR28
1.4099312  Ok
1E 50 FOR28
1.4138177  Ok
1E 100 FOR28
1.4140730  Ok
1E 500 FOR28
1.4142010  Ok
1E 1000 FOR28
1.4142091  Ok
1E 5000 FOR28
1.4142132  Ok
1E 10000 FOR28
1.4142134  Ok
1E 20000 FOR28
1.4142135  Ok
It took about 10,000 iterations to get six exact decimal places.

Example twenty nine. In line two we calculate the difference (B-A) - the length of the segment. In the third we transfer N to the real stack. In the fourth, calculating the quotient (B-A)/N, we obtain the length of each divided segment and in the fifth we display this on the screen. In the sixth we display the first point (coordinates A), then in the loop we add the length of the broken segment, we get the next point, and we display this value. After the loop, we delete the two remaining values ​​(the length of the segment and the last point).
: FOR29 ( I: N>1 F: A B [A<B] -> )  \ выводим: H A A+H ... A+N*H
FOVER F-                      \ F: A B -> A B-A
DUP S>D D>F                   \ I: N -> F: A B-A N
F/ FDUP                       \ F: A B-A N -> A (B-A)/N (B-A)/N
." Длина отрезка H = " F. CR  \ F: A (B-A)/N (B-A)/N -> A (B-A)/N
FSWAP FDUP F.                 \ A (B-A)/N -> (B-A)/N A
1+ 1                          \ I: N -> N+1 1
DO                            \ N+1 1 ->
    FOVER F+                  \ (B-A)/N A -> (B-A)/N A+(B-A)/N
    FDUP F.                   \ дублируем и печатаем «A+(B-A)/N»
LOOP FDROP FDROP ;            \ (B-A)/N A+(B-A)/N –>, очищаем вещественный стек после себя
\ Тест вышеописанного слова:
3 1.2E 1.5E FOR29
Длина отрезка H = 0.1000000
1.2000000 1.3000000 1.4000000 1.5000000  Ok
Example thirty. We write a new word called “F(X)”, which calculates the value of the function “1-sin(X)” and displays the result on the screen. The word “FOR30” itself is a twin of “FOR29”, the only difference is the replacement of the “F.” pin. (in lines six and ten on "F(X)").
: F(X) ( X -> )  \ вывести значение «1-sin(X)»
FSIN FNEGATE 1E F+ F. ;      \ X -> [1-sin(X)]
: FOR30 ( I: N>1 F: A B [A<B] -> )
FOVER F-                     \ F: A B -> A B-A
DUP S>D D>F                  \  I: N -> F: A B-A N
F/ FDUP                      \ F: A B-A N -> A (B-A)/N (B-A)/N
." Длина отрезка H= " F. CR  \ F: A (B-A)/N (B-A)/N -> F: A (B-A)/N
FSWAP FDUP F(X)              \ F: A (B-A)/N -> F: (B-A)/N A
1+ 1                         \ I: N -> N+1 1
DO                           \ N+1 1 ->
    FOVER F+                 \ (B-A)/N A -> (B-A)/N A+(B-A)/N
    FDUP F(X)                \ дублируем и обрабатываем «A+(B-A)/N»
LOOP FDROP FDROP ;           \ (B-A)/N A+(B-A)/N –>, очищаем вещественный стек после себя
 

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

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

Example eleven. Find the sum of squares from N to 2* N. The scheme of work is similar to the previous examples, we also set up a counter on the stack, the limits of the loop parameter are absolutely the same, before summing we square each element.

: FOR11 ( N>0 -> ) \ N^2+[N+1]^2+[N+2]^2+…+[2*N]^2
0 \ N -> N 0 = Sum – total amount
OVER 1+ 0 \ N>0 Sum -> N Sum N+1 0 – the last 2 numbers are the limits of the cycle
DO\N Sum N+1 0 -> N Sum
    OVER I + DUP * + \ N Sum -> N Sum+(N+I)^2
LOOP. DROP; \ Sum – print the result, N – delete the excess
\ Test example eleven:
3 FOR11
86 OK
4 FOR11
190 Ok
5 FOR11
355 OK

Let's check for three: (3+0)^2+(3+1)^2+(3+2)^2+(3+3)^2= 9+16+25+36=86 – everything is correct.

Example twelve. Find the product of N factors 1.1*1.2*…. Here, in a loop for N elements, you need to calculate each one using the formula (1+0.1*N) and multiply it with the total value of the product, the initial value of which will be one.

: FOR12 ( N>0 -> ) \ 1.1*1.2*1.3*...
1+ 1 \ I: N -> N+1 1
1E\F: 1=P
DO\I: N+1 1 ->
    I 0 D>F 10E F/ 1E F+ \ F: P -> P 1+0.1*I
    F* \ P 1+0.1*I -> P*(1+0.1*I)
LOOP F. ; \ P*(1+0.1*I) – print the final product
\ Tests for the twelfth example:
1 FOR12
1.1000000 Ok
2 FOR12
1.3200000 Ok
3 FOR12
1.7160000 Ok
4 FOR12
2.4024000 Ok
5 FOR12
3.6036000 Ok

1.1 is the first element (1 FOR12), for two elements we get (1.1*1.2)=1.32 (2 FOR12), for three - we multiply the previous one by 1.3 we get (1.1*1, 2*1.3)=1.716 (3 FOR12), then check it yourself.

Example thirteen. Similar to the previous one, we replace the product with a sum and for each element we change the sign to the opposite, multiplying by minus one. To do this, we create a variable, which we initialize to one, then after calculating the next member of the series, we change its sign.

FVARIABLE S\S – SIGN variable sign
: FOR13 ( N>0 -> ) \ 1.1-1.2+1.3-...
1E S F! \ initially assign one, each time the word is called again
1+ 1 \ I: N -> N+1 1 – cycle parameter limits
0E\F: 0 = Sum
DO\I: N+1 1 ->
    I 0 D>F 10E F/ 1E F+ \ F: Sum -> Sum 1+0.1*I
    S F@ FDUP FNEGATE S F! F* \ F: Sum 1+0.1*I -> Sum (1+0.1*I)*S , S = - S
    F+ \ Sum (1+0.1*I)*S -> Sum+(1+0.1*I)*S
LOOP F. ;
\ Traditionally, a test word that will help you avoid entering the same type of data many times:
: TEST-FOR13 10 1 DO I DUP . FOR13 CR LOOP ;
TEST-FOR13
1 1.1000000
2 -0.1000000
3 1.2000000
4 -0.2000000
5 1.3000000
6 -0.3000000
7 1.4000000
8 -0.4000000
9 1.5000000
 Ok

Example fourteen. We calculate the square of a number using the formula (sum of the series) without using multiplication. The word must print the squares of all integers from 1 to N inclusive.

: FOR14 ( N>0 -> ) \ N^2=1+3+5+...+{2*N-1}
1+ 1 0 ROT ROT \ N -> 0 N+1 1 - standard cycle parameter limits
DO \ 0 N+1 1 -> 0=Sum – sum of the series
    I 2* 1- + DUP . \ Sum -> Sum+(2*I-1) – current sum of the series, duplicate and print
LOOP DROP ; \ before exiting, leave the stack as it was, removing the original parameter
\ Test word for automatic testing, displays the following beautiful data:
: TEST-FOR14 11 1 DO I FOR14 CR LOOP ;
TEST-FOR14
1
14
1 4 9
1 4 9 16
1 4 9 16 25
1 4 9 16 25 36
1 4 9 16 25 36 49
1 4 9 16 25 36 49 64
1 4 9 16 25 36 49 64 81
1 4 9 16 25 36 49 64 81 100
 Ok

Example fifteen. Raise a given real number to an integer power by multiplying by itself the appropriate number of times.

: FOR15 ( F: A I: N>0 -> ) \ 1.5E 5 FOR15 – word usage format, outputs A^N
1E \ F: A –> A 1=P – power of the original number, initially equal to one
0 \ I: N>0 -> I: N>0 0 - lower limit of the loop parameter
DO
    FOVER F* \ A P -> A P*A – simply P equal to one multiplied 15 times by A
LOOP F. FDROP ; \ Print the degree and delete the original number A
\ Let's test by raising two to the power from 1 to 10, using a test word:
: TEST-FOR15 11 1 DO 2E I FOR15 LOOP ;
TEST-FOR15
2.0000000 4.0000000 8.0000000 16.000000 32.000000 64.000000 128.00000 256.00000 512.00000 1024.0000 Ok

A small joke in the work of the word FOR15, since both parameters of the word are on different stacks, it does not matter in what order they are entered, which means that the examples

2E 1 FOR15
1 2E FOR15

will give the same and correct result, despite the incorrect syntax and logic.

In Forth, you can raise a number to a power in a more traditional way “in one action”:

: FOR15 ( F: A N -> ) \ A^N
F**F. ;
2E 10E FOR15
1024.0000 Ok

Two to a tenth 1024. Here the order is important and both parameters are real, because for an integer it is necessary to transfer it to a real stack. The code has become much shorter, but the first option serves as a clear example of how loops work, rather than effectively raising a number to a power.

Example sixteen. We get from the previous one with small changes. Now we print the result not just once (at the end after “LOOP”), but each time inside the loop, after calculating the next degree “FOVER F*”.

: FOR16 ( F: A I: N>0 -> ) \ 1.5E 5 FOR15 – word usage format, outputs A A^2 ... A^N
1E \ F: A –> A 1=P – power of the original number, initially equal to one
0 \ I: N>0 -> I: N>0 0 - lower limit of the loop parameter
DO
    FOVER F* FDUP F. CR \ A P -> A P*A – duplicate P*A and display it on the screen
LOOP FDROP ; \ remove the original number A
\ Example of how a word works:
2E 10 FOR16
2.0000000
4.0000000
8.0000000
16.000000
32.000000
64.000000
128.00000
256.00000
512.00000
1024.0000
 Ok
\ If we remove “CR” in the loop after outputting the next degree, we get:
2E 10 FOR16
2.0000000 4.0000000 8.0000000 16.000000 32.000000 64.000000 128.00000 256.00000 512.00000 1024.0000 Ok

The word test from example 15 (TEST-FOR15) is absolutely identical to how it works.

Example seventeen. Now we simply sum up the derived degrees in the previous example and output one result. We use a variable of real type; we will store the total amount in it.

FVARIABLE F1
: FOR17 ( F: A I: N>0 -> ) \ 1.5E 5 FOR17 – word call form, output 1+A+A^2+A^3+...+A^N
1E FDUP F1 F! \ 1 = P – degree A is first assigned one, duplicated and saved in F1
0\N -> N 0 - lower bound of the cycle
DO\N0 ->
    FOVER F* FDUP \ F: A 1 -> A 1*A 1*A
    F1 F@ F+ F1 F! \ F1=1*A+F1
LOOP
F1 F@ F. FDROP FDROP ; \F1. – printout of the result, removal of unnecessary data

Let's test for A=2 (in this case we will get very interesting numbers), run the test word from 1 to 10, I think this should be enough.

: TEST-FOR17 11 1 DO 2E ." N=" I DUP . FOR17 CR LOOP ;
TEST-FOR17
N=1 3.0000000
N=2 7.0000000
N=3 15.000000
N=4 31.000000
N=5 63.000000
N=6 127.00000
N=7 255.00000
N=8 511.00000
N=9 1023.0000
N=10 2047.0000
 Ok

Experiment with other foundations yourself.

Example eighteen. We obtain from the previous one by multiplying each term of the sum by minus one in a loop, thus changing its sign we get an alternating series (as in the condition).

FVARIABLE F1
: FOR18 ( F: A I: N -> )  \ 1.5E 5 FOR18 – пример вызова, результат 1-A+A^2-A^3+...+(-1) ^N*A^N
1E FDUP F1 F!       \ F: A -> A 1=P – дублируем 1 и сохраняем в F1 = сумма ряда
0                   \ I: N -> N 0 – границы параметра цикла
DO                  \ N 0 ->
    FOVER F*        \ A P -> A P*A
    -1E F* FDUP     \ A P*A -> A P*A*(-1) P*A*(-1)
    F1 F@ F+ F1 F!  \ F1=F1+(P*A*(-1))
LOOP
F1 F@ F.            \ распечатка итоговой суммы ряда
FDROP FDROP ;       \ очистка оставшихся данных
: TEST-FOR18 11 1 DO 2E I DUP . FOR18 CR LOOP ;
\ Результат работы тест слова TEST-FOR18:
TEST-FOR18
1 -1.0000000
2 3.0000000
3 -5.0000000
4 11.000000
5 -21.000000
6 43.000000
7 -85.000000
8 171.00000
9 -341.00000
10 683.00000
 Ok

Two's squares: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024.

We get the series: 1-2=-1; -1+4=3; 3-8=-5; -5+16=11; 11-32=-21; -21+64=43; 43-128=-85; -85+256=171…

Example nineteen. We calculate the factorial in real format (so to speak, we determine its order, and not the exact integer value).

: FOR19 ( N>0 -> ) \ N! – print factorial
1+ 1 \ N –> N+1 1 – cycle parameter limits
1E \ F: 1E=Fact – the value of the factorial is initially equal to one
DO\N+1 1 ->
    I 0 D>F F*
    \ F: Fact -> Fact*I – I is converted into a double precision word by simply adding
    \ zero, so that we can then transfer it to the real stack, and multiply by Fact
LOOP
G. ; \printout of the result

The "F" word changed it to “G.” so that there is an indicator. Since the format of the first one does not show it. Final work word test:

: TEST-FOR19 20 1 DO I DUP . ." != " FOR19 CR LOOP ;
TEST-FOR19
1 != 1.0000000
2 != 2.0000000
3 != 6.0000000
4 != 24.000000
5 != 120.00000
6 != 720.00000
7 != 5040.0000
8 != 40320.000
9 != 362880.00
10 != 3628800.0
11 != 39916800.
12 != 4.7900160e08
13 != 6.2270208e09
14 != 8.7178291e10
15 != 1.3076744e12
16 != 2.0922790e13
17 != 3.5568743e14
18 != 6.4023737e15
19 != 1.2164510e17
 Ok

Example twenty. We can get it from the previous one with a small modification. Add S - the sum of factorials (line three). And in the ninth line we add the current factorial to this amount. Before printing the answer, reset the last current factorial.

: FOR20 ( N>0 -> )  \ 1!+2!+…+N! – вывести сумму факториалов
1+ 1        \ I: N –> N+1 1 – пределы параметра цикла
0E          \ F: 0E= S – значение суммы факториалов вначале равно нулю
1E          \ F: S -> S 1=F - текущий факториал
DO          \ N+1 1 ->
    I 0 D>F F*
    \ F: S F -> S F*I – I переводим в слово двойной точности, просто добавив
    \ ноль, чтобы потом перевести его на вещественный стек, и умножаем на F
    FSWAP FOVER F+ FSWAP             \ S F*I -> S+F*I F*I
LOOP
FDROP G. ;  \ распечатка результата
\ Тест слово для FOR20 на диапазоне данных от 1 до 10:
: TEST-FOR20 21 1 DO I FOR20 CR LOOP ;
TEST-FOR20
1.0000000
3.0000000
9.0000000
33.000000
153.00000
873.00000
5913.0000
46233.000
409113.00
4037913.0
43954713.
5.2295631e08
6.7499771e09
9.3928268e10
1.4016026e12
2.2324393e13
3.7801182e14
6.7803855e15
1.2842549e17
2.5613275e18
 Ok