Khiryanov Timofey Fedorovich
The main algorithmic constructions, in addition to elementary operations represented by one element of the circuit, are alternative execution and cycles. There are two alternative programming options and there are three main cycle types.
Conditionally executable code
Some operations may be subject to conditional operator. Then they will be executed only if this condition is true.if<условие>
then
<действия>
all
Alternative
In a flowchart, a condition test can serve as a principle for selecting alternative operations. That is, if the condition is true, the execution will go along one trajectory, and if it is false, then along the other. In the KuMir language, a loop with a precondition has the following form:if<условие>
then
<действия>
otherwise
<альтернативные действия>
all
Conditions for the robot:
left wall
right wall
bottom wall
top wall
the cell is shaded
left free
right free
bottom loose
top loose
cage clean
Loop with precondition
A loop with a precondition is a loop that is executed while some condition specified before its start is true. This condition is checked before the execution of the loop body, so the body may not be executed even once (if the condition is false from the very beginning). In most procedural programming languages, it is implemented by the while statement, hence its second name is the while loop. In the KuMir language, a loop with a precondition has the following form:nts bye<условие>
<тело цикла>
kts
Loop with postcondition
A loop with a postcondition is a loop in which the condition is checked after the execution of the loop body. It follows that the body is always executed at least once. In Pascal this loop is implemented by the repeat..until operator, in C it is do…while .In the KuMir language, a loop with a postcondition has the following form:
nc
<тело цикла>
cc_at<условие>
Loop with counter
A loop with a counter is a loop in which some variable changes its value from a given initial value to a final value with some step, and for each value of this variable, the body of the loop is executed once. In most procedural programming languages, it is implemented by the operator for, which indicates the counter (the so-called " loop variable”), the required number of passes (or the limit value of the counter) and, possibly, the step in which the counter changes. In the KuMir language, a cycle with a counter has the following form:In different programming languages, the question of the value of a variable at the end of a loop in which this variable was used as a counter is solved differently.whole
nc for a from 0 to 9
... loop body
kts
Acquaintance with the program Kumir mastering the basics of programming.
In it, students can gain practical skills in creating and debugging an algorithm, working with performers such as Robot, Draftsman, Aquarius, Grasshopper, Turtle.
When studying one of the most difficult sections of computer science "algorithmization and programming".
Purpose of development :
Download:
Preview:
Methodical development in informatics.
Topic: "Robot performer in the KuMir program at informatics lessons"
technology teacher "Informatics and ICT"
Explanatory note
Development goal: to study the possibilities of programming on the example of a specific executor Robot using the KUMIR environment; give practical skills to work with the performer.
Methodical developmentcompiled for informatics lessonsPractice on the computer: work with the educational executor of algorithms; drawing up linear, branching and cyclic algorithms for managing an executor; drawing up algorithms with a complex structure; use of auxiliary algorithms (procedures, subroutines).
Students should know:
- what is a performer; SKI Robot, Wednesday performer Robot;
- what is an algorithm;what are the main properties of the algorithm;
- ways of writing algorithms: flowcharts, educational algorithmic language;basic algorithmic constructions: following, branching, loop; structures
- algorithms; ⇒ assignment of auxiliary algorithms; technologies for building complex algorithms:
Students should be able to:
- understand descriptions of algorithms in a learning algorithmic language;
- perform an algorithm trace for a known performer;
- compose linear, branching and cyclic control algorithms for the Robot executor; allocate subtasks; define and use auxiliary algorithms.
Session 1 (2 hours) Lesson 1.
Performer Robot.Executor command system.
Lesson plan.
- Description of the executor's UCS, the executor's environment.
2. Analysis of typical robot algorithms.
During the classes.
Consider the description of the performer.
Executor environment: Performer The robot is able to move through the labyrinth, drawn on a plane divided into cells.
SKI Robot : simple commands: up, down, left, right, fill.
Logic commands: (condition checks)
top free bottom free
left free right free.
Logical connectives: AND, NOT, OR:
Example: (Not left free) or (Not right free)
Branch command: cycle command:
If condition then nts while condition
series of commands series of commands
all kts
(In CIMs of 2009, the commands of the Robot differed from those familiar to children, which led to confusion :)
Branch command: cycle command:
If condition then nts while condition do
series of commands series of commands
end end
General view of the Kumir program window. Graphical environment of the Robot:
in KIMs demo version 2010 command format changed to habitual
The order of creating the algorithm:
1.Teams Tools -Edit starting environmentdraw walls on the Robot field and set the Robot to its initial position.
2.Commands Robot - Change starting environmentsave the new environment.
3.Commands Paste- Use Robotspecify the artist.
4. In the document window, write the algorithm using the menu Insert.
5. Commands Execution - execute continuously (or step by step) run the algorithm.
6. Consider the result of the algorithm execution and, if necessary, debug it.
Lesson 1 (2 hours) Lesson 2.
Practical work "Compilation of linear algorithms.
Tasks: 1. Robot at an arbitrary point in the field. Color the cell above, below and to the right of the starting position.
- Robot at an arbitrary point in the field. Move the Robot 4 spaces to the right, painting over them.
- Create a new starting environment by drawing a 4-cell square on the board. Save the environment as a start.
- Create a new starting environment by drawing a corridor with passages in the walls on the field. Save the environment as obst2.fil. Change the starting environment to the newly created one.
Session 2 (2 hours) Lesson 1.
Topic : Branching and sequential refinement of the algorithm.
Analysis of CIM tasks using the Robot executor.
use robot
alg kim 2009
early
if not bottom loose
then to the right
all
if not bottom loose
then to the right
all
if not bottom loose
then to the right
all
con
use robot
alg kim 2010
early
if not bottom loose
then to the right
all
if not bottom loose
then to the right
all
if not bottom loose
then to the right
all
con
Etc. slave. No. 14. Compilation and debugging of branching algorithms
Tasks. See Attachment.
Lesson 3. Cyclic algorithms. Lesson 1-2
Target: reveal the essence of the concept of a cycle in algorithms, show the forms of writing cycles in algorithms, give skills in creating and writing cyclic algorithms.
Etc. slave. No. 15. Compilation and debugging of cyclic algorithms
1. Make an algorithm that paints all the inner cells adjacent to the wall.
use robot
alg
early
nc while right free
paint over; right
kts
nc while the bottom is free
paint over; way down
kts
nc until the bottom loose
paint over; to the left
kts
con
2. Create an algorithm that fills all the cells between the Robot and the wall. The distance to the wall is unknown.
use robot
alg
early
nc while right free
right; paint over
kts
con
3. Create an algorithm that paints over all the cells between two walls.
use robot
alg uch3
early
nc yet (not top loose) or (not bottom loose)
right
if (not top free) and (not bottom free)
then
paint over
all
kts
con
4. Create an algorithm that fills all the cells around a rectangular wall.
alg uch4
early
paint;up
nc until right loose
paint;up;
kts
paint;right
nc until the bottom loose
paint;right;
kts
paint over;down
nc until left loose
paint;down;
kts
paint;left
nc until top loose
paint over; left;
kts
con
use robot
alg uch5
early
right
nc until the bottom loose
paint over; right
kts
paint over; way down
nc while left free
paint over; to the left
kts
nc until left loose
paint over; way down
kts
paint;left;paint; up;
nc while top free
paint over; up
kts
nc until top loose
paint over; to the left
kts
con
Activity 4 Lesson 1
Helper Algorithms.
Target: introduce the concept of the main and auxiliary algorithm; explain the rules for using the auxiliary algorithm; parse examples of algorithms using an auxiliary.
Lesson Plan
1.Introduction of new terms (main and auxiliary algorithm, call) and explanation of new concepts.
2. Analysis of examples of solving problems using an auxiliary algorithm.
When solving some problems, it is convenient to break them into smaller subtasks, each of which can be designed as an independent algorithm. In this case, the so-called main algorithm is first compiled, in which calls to auxiliary algorithms are used to solve subtasks, which are added later. This kind of solution is calledsequential refinement method.It allows a group of programmers to work on a project, while each one solves his own subtask.
In the process of solving the problem, each auxiliary algorithm can, if necessary, be divided into smaller auxiliary algorithms.
The command to execute the auxiliary algorithm is called challenge and is written in the body of the main algorithm.
One and the same algorithm can be considered as the main and auxiliary in relation to other algorithms. In an algorithmic language, the main algorithm is written first, and auxiliary ones are written in a row below.
Task 1:
The robot is in the upper left corner of the field. There are no walls or shaded cells. Compose an algorithm, using an auxiliary one, drawing four crosses on one horizontal line. The final position of the Robot can be arbitrary.
Solution
Analysis on the board:
Task2. The robot is in the upper left corner of the field. There are no walls or shaded cells. Write an algorithm that paints an 8 x 8 square in a checkerboard pattern. The final position of the Robot can be arbitrary.
Activity 4 Lesson 2
Practical work on a PC "Problem solving using auxiliary algorithms".
Target : to instill practical skills in constructing algorithms by the method of sequential refinement.
Lesson Plan
1. The task is completely completed by the PC. Students receive tasks and complete them in the Kumir software environment. The results of the Work are saved as files for later verification.
Task1 . The robot is in the lower left corner of the field. There are no walls or shaded cells. Write an algorithm that paints 6 vertical stripes of the same length in 6 cells. The final position of the Robot can be arbitrary.
Task2 .Using auxiliary, make an algorithm for painting over the cells that form the number 1212.
Homework: Come up with an algorithm that draws the following image: Apply two auxiliary algorithms to solve the problem.
Activity 5 Lesson 1-2
Test
"Compilation of the algorithm in the environment of the executor Robot".
Target: to test the acquired knowledge on the creation and ability to analyze algorithms in the Kumir software environment.
Tasks for control work are divided by difficulty levels and includes 3 tasks with the executor Robot (tasks 1 and 2 - for branching and loops, task 3 - for using an auxiliary algorithm.) The texts of the tasks are given in the appendix.
The initial and final conditions and the created algorithms are recorded as a file.
The grade is set according to the level of difficulty of the task. The student has the right to choose the type of task.
1. Introduction
the system "KuMir" (the name comes from the words "Set of Educational Worlds"), with which this electronic version of the textbook will introduce you.
The developers of the "KuMir" language pursued the goal of creating a simple language for the initial course of computer science that meets modern programming technology and allows production use. The school algorithmic language was taken as a basis. The language was supplemented with some features that turn it from educational to production. The language has:
types whole, thing, lit; the traditional set of operations on data of these types (including operations on strings and standard set mathematical functions);
arrays ( tab) specified types; structural control structures of cycles, branching, etc.
Kumir is open - connecting external executors enriches the language with new features: from database management and working with geometric objects to expanding the set of valid numeric types (in this case, the language will allow mixing new types with existing numeric types in expressions).
Modern technology Programming teaches us to break down a program not only into subprograms, but also into larger units: sets of programs that work on common data. AT different languages programming, such units are called differently, in KuMir such a unit is called "Executor". The concept of a performer is extremely important in practical work, and should be introduced at the earliest possible stages of training.
The experience of using KuMir in teaching and for developing educational software has shown that the language is easy to learn and at the same time powerful enough to expand a wide class of production tasks.
Like the E-workshop, KuMir is an integrated system that includes text editor, an incremental compiler with zero response time, as well as a simple and convenient debugger. good name for a system of this kind - "Editor-Compiler": while you are entering your program, the compiler processes it, and at any moment the program is ready to be executed without the slightest delay.
2. Names and types of value. KuMir Operations
Any characters of the Russian and Latin alphabets, as well as numbers, can be used in writing variable names. The name must not start with a number. There are no strict restrictions on the length of names in the KuMir system, but for ease of editing and to avoid overflowing lines, variables and algorithms should not be given too long names. Usually the name is chosen so that you can understand what the algorithm is intended for. When editing programs, it should also be remembered that Russian and Latin letters, similar in spelling, are distinguished by computers. For example, if when describing a variable named A, the user typed "A" in the Latin alphabet, and in the text of the algorithm he tries to access this variable by typing its name in the Russian alphabet, then in this line the "name is not defined" message will appear in the "fields" . |
A constant value (constant) does not change its value during the execution of the algorithm.
A variable can change its value during the execution of the algorithm.
Expression- a record that defines the sequence of actions on values. An expression can contain constants, variables, operation signs, functions.
The following symbols are used to write expressions in Kumir:
To indicate signs logical operations symbols are used:
= equal;
< >not equal;
< меньше;
> more;
< = меньше или равно;
> = greater than or equal;
For the record difficult conditions operations such as: And, OR NO.
AND - simultaneous fulfillment of the above conditions (Х > 0 and Х< = 2);
OR- fulfillment of at least one of the conditions (X > 0 or Y > 0);
NOT- denial.
3. Built-in functions of the KuMir language
Here is an example of built-in functions:
Appeal | Function | Types |
|
Argument | Functions |
||
SIN(x) cos(x) T. G. (x) EXP(x) LN(x) ABS (x) SQRT(x) MOD(A,b) int(x) PI | sine x cosine x tangent x | thing | thing |
An example of writing arithmetic expressions in an algorithmic language:
4. INPUT / OUTPUT commands
It is often required to organize an exchange of information ("dialogue") between a person and a computer in the process of executing an algorithm. To do this, the algorithmic language has special commands for OUTPUT information from the computer memory to the screen and INPUT information from the keyboard (from a person) into the computer memory.
ENTER command - a command by which the values of variables are set through input devices (keyboard).
OUTPUT Command- a command by which the value of the value is reflected on the output device of the computer (monitor screen).
Since values are used in the algorithmic language to store information, the input / output commands indicate the names of the quantities whose values must be displayed (displayed on the screen) or entered (remembered in the computer memory).
Example:
Official word NS (new line) tells the computer that the information should be output on a new line.
5. Assignment command. Creation and editing of linear structure programs
In order to remember or change the value of a quantity, there is a special command in the algorithmic language - assignment instruction, which is written as:
VALUE NAME: = EXPRESSION
The sign ":=" (a colon followed by an equal) is called a sign assignments and is read as "assign" (for example, the command "n:=e" reads "n assign e"). When executing an assignment command, the computer first calculates the expression written on the right side (replacing the names of the quantities with their values), and then writes the resulting value of the expression into memory.
Algorithms that are a simple sequence of actions are called linear structure algorithms.
Consider the creation process linear algorithm on the example of the calculation of the expression:
1. Calculate the sum of two numbers
2. Write a program for finding the hypotenuse of a right triangle given two legs
3. Find the volume of a cube if its side is known
6. Creating and editing branching structure programs
Problem solving cannot always be represented as a linear algorithm. There are tasks in which it is required to organize the choice of performing a sequence of actions depending on any conditions. Such algorithms are called branching structure algorithms. In the KuMir programming system, to create an algorithm for a branching structure, the constructions "IF - THEN - ELSE - ALL" and "CHOICE - IF - ALL" are provided.
Branch command: IF - THEN - ELSE - ALL
Branch command - splits the algorithm into two paths depending on some condition; then the execution of the algorithm goes to a common continuation. Branching is complete and incomplete.
Graphic scheme of the construction " if"
Service words " if", "then", "otherwise" have the usual meaning. The word " all" means the end of the construction. Between " then" and " otherwise" - in one or more lines - a sequence of commands of the algorithmic language is written (series 1). Between " otherwise" and " all"another sequence of commands is recorded (series 2). Series 2 together with the service word " otherwise" may be missing. When executing the " if"The computer first checks the condition written between " if" and " then". As a result of the check, either YES, or NO. If possible YES, then SERIES 1 is executed, and if NO, - then SERIES 2 (if any) .
If the condition is not met (it will turn out NO), and series 2 along with " otherwise" is absent, then the computer immediately proceeds to execute the commands written after the word " all".
7. Types of cycles in the KuMir programming system
Algorithms whose individual actions are repeated many times are called algorithms of a cyclic structure. The set of actions of the algorithm associated with repetition is called a cycle.
Loop command provides repeated execution of a sequence of commands (loop body) according to some condition.
For programming algorithms of a cyclic structure in the KuMir programming system, two types of loops are provided: a loop with a precondition (loop for while) and a loop with a parameter (loop for).
Loop with precondition (while loop)
A loop with a precondition (while loop) is a loop whose execution is repeated while the loop condition is true. Service words NC(beginning of cycle) and KC(end of the cycle) are written strictly one under the other and connected vertical bar. To the right of this line, a repeated sequence of commands (loop body) is written.
When it is executed, the computer cyclically repeats the following actions:
a) checks written after the word bye condition;
b) if the condition is not met (the condition is false), then the execution of the cycle ends and the computer starts executing the commands written after KC. If the condition is met (the condition is true), then the computer executes the loop body, checks the condition again, and so on.
If the condition in the loop bye is not observed from the very beginning, then the body of the loop is never executed.
Comment. Loop execution bye may not terminate if the condition is true all the time (this situation is called a loop). Therefore, in order to avoid such situations, the body of the loop should contain commands for changing the condition.
Given a positive integer N. Calculate the factorial of this number: N! = 1 * 2 * 3 * ... * N.
Loop with parameter (loop for)
Loop with parameter(loop for) - repeated execution of the loop body while the integer parameter runs through the set of all values from the initial (i1) to the final (in):
Here i is a variable of an integer type, called a loop parameter: i1, in are the initial and final values of the loop parameter, which can be specified either by arbitrary integers or by expressions with integer values; h - step of changing the cycle parameter value, the step value can be any integer (both positive and negative). The entry "step h" in the first line may be absent altogether, while the default value of the step is 1.
When executing a loop for, its body is executed for i = i1, i = i1 + h, i = i1 + 2*h, . . . , i = in. The rules of the algorithmic language allow specifying any integers i1, in, h. In particular, in may be less than i1. If, in addition, the value of h< 0, то цикл выполняется нужное количество раз, а если h имеет положительное значение, то этот случай не считается ошибочным - просто тело цикла не будет выполнено ни разу, а ЭВМ сразу перейдет к выполнению команд, записанных после KC. For h = 0, looping occurs.
Example: Given a positive integer N. Calculate the factorial of this number: N! = 1 * 2 * 3 * ... * N.
8. Algorithms for recurrent expressions
In mathematics and computer science, there are often sequences in which each subsequent term is calculated through the previous ones.
AT arithmetic progression, for example, each next term is equal to the previous one, increased by the difference of the progression:
ai =ai-1 +d
In sequence 1, 1, 2, 3, 5, 8, 13, ... ( it's called the Fibonacci sequence) each next term is equal to the sum of the two previous ones. For this sequence
ai = ai-1 + ai-2 , a1 = a2 =1
Formulas that express the next member of a sequence in terms of one or more previous members are called recurrent relations.
9. Table values and work with them
To record algorithms that work with a large amount of information, in the algorithmic language there are special tabular values called tables (arrays).
Table values are made up of other values, usually integers or real values, called elements. Elements in the table can be arranged in different ways. The algorithmic language of the KuMir programming system uses the 2 most common types of tables: linear and rectangular tables.
Working with linear tables (one-dimensional arrays)
Like any value linear table occupies a place in the computer memory, has a name, value and type. KuMir uses tables of integer (celtab) and real (vehtab) types. For example:
The record celtab A [ 1: 5 ] means that the value A is a table (tab) consisting of integers (integers), the elements of this table have indices from 1 (lower limit) to 5 (upper limit). The value of A is five integers: 3, 15, 0, -10.101.
Table elements do not have separate names. To designate the i-th element of table A, the record A [ i ] is used. For example, when executing the command A [ 3 ] : = A [ 2 ] + A [ 4 ] the computer will substitute instead of A [ 2 ] and A [ 4 ] the values of the 2nd and 4th elements of table A, i.e. the number 15 and -10, add them up and assign the resulting value to the 3rd element, thus, instead of 0, the value 5 will appear instead of 0 in the place of the 3rd element in the table.
Any (both positive and negative) integers, as well as 0, can be used as table border values. The value of the lower border must be less than the value of the upper border; if they are equal, the table is considered to consist of one element. If in the description of the table, due to a typo, the lower bound turns out to be greater than the upper one, for example, celtab [ 3: 1], then this will not be considered an error, and when entering the algorithm, no messages will appear in the "fields". In this case, it will be considered that there is not a single element in this table, and the message "bad index" will appear the first time this table is accessed.
A task.
Working with rectangular tables (matrices)
Like a linear table, a matrix takes up space in the computer's memory, has a name, a value, and a type. KuMir uses tables of integer (celtab) and real (vehtab) types.
The notation celtab A [ 1: 5, 1:2 ] means that the value A is a table (tab) consisting of integer (integer) numbers, the elements of this table have indices from (first column, first row) to (last column, last line). The value of A is ten integers: 3, 15, 0, -10, 101, 200, -45, 50, 10, 222.
Table elements do not have separate names. To designate the i-th element of table A, the record A [ i, j ] is used. For example, when executing the command A [ 3, 1 ] : = A [ 2, 1 ] + A [ 4, 1 ] the computer will substitute instead of A [ 2, 1 ] and A [ 4, 1 ] the values of the 2nd and 4th elements of the first column of table A, i.e. the numbers 15 and -10, will add them up and assign the resulting value to the 3rd element in the first row, so that instead of 0, the value 5 will appear in place of the 3rd element of the first row in the table.
Any (both positive and negative) integers, as well as 0, can be used as table border values. The value of the lower border must be less than the value of the upper border; if they are equal, the table is considered to consist of one element. If in the description of the table, due to a typo, the lower bound turns out to be greater than the upper one, for example, celtab [ 3: 1, 5: 2], then this will not be considered an error, and no messages will appear in the "fields" when entering the algorithm. In this case, it will be considered that there is not a single element in this table, and the message "bad index" will appear the first time this table is accessed.
A task. In the given table B, determine the index and value of the maximum element.
Appendix: Tasks
Linear Algorithms
Task #1
Find the sum of two numbers - a and b
Solution:
alg
sum
early
thing
a, b, c
conclusion
"enter the value of 2 numbers"
input
a, b
c:= a + b
conclusion
ns
, "sum of numbers",a,"and",b,"equal to",c
con
Task #2
Find the difference of two numbers
Solution:
alg
difference
early
thing
a, b, c
conclusion
" enter variable values "
input
a, b
c:= a - b
output ns,
" difference of numbers",a,"and",b," equals",c
con
Task #3
Find the product of any two natural numbers
Solution:
whole a, b, c
alg
work
early
conclusion
"
enter two numbers"
input
a,bc:=a +b
output ns,"
product of numbers",a,"and",b"equals",c
con
Task #4
Find the quotient of two natural numbers
Solution:
thing a, b, c
alg
private
early
conclusion "
enter dividend and divisor"
input
a, b
c:= a / b
output ns,
"quotient",a,"and",b,"equal to",c
con
Task #5
Find the arithmetic mean of five arbitrary numbers
Solution:
thing a, b, c, d, e, f
alg
arithmetic
start things
a, b, c, d, e, f
conclusion
"Enter any 5 numbers"
input
a, b, c, d, e
f:=(a + b + c + d + e)/ 5
conclusion ns
," the arithmetic mean of 5 numbers is", f
con
branching
Task #1
Find the largest among 3 integers (numbers are arbitrary)
alg
maximum
early target
a B C
conclusion
"Enter three random numbers"
input
a B C
if
a>b>c
then the conclusion is ns
," the maximum number is", and
all
if
a<б>With
then the conclusion is ns
," the maximum number is", b
all
if
a<б<с
then the conclusion is ns
," the maximum number is", with
all
con
Task #2
You are given two arbitrary numbers. If the first number is greater than the second, then assign their sum to it, and their product to the second number. If the second number is greater than the first, then assign their product to the first number, and their sum to the second.
alg
condition
start things
a, b
conclusion
"Enter two numbers"
input
a, b
if
a > b
then
a:= a + b
b := a * b
otherwise
a:= a * b
b := a + b
conclusion ns
, a, b
con
Task #3:
Find among 4 arbitrary numbers the minimum
Solution:
alg
minimum
start things
a, b, c, e
conclusion
"Enter 4 random numbers"
input
a, b, s. e
if
a>b>c>e
then the conclusion is ns
," maximum number-",and
all
if
a<б>c>e
then the conclusion is ns
,"maximum number -",b
all
if
a<б<с>e
then the conclusion is ns
," maximum number -", s
all
if
a<б<с<е
then the conclusion is ns
, "maximum number -", e
all
con
Task #4
Given 2 legs (2 cm and 2 cm) of an isosceles triangle and its base (2.82 cm). Determine if the triangle is a right triangle.
Solution:
alg
triangle
start things
i, h, s
i:= 2
h:= 2
c:= 2.82
if
c**2= (i**2)+(h**2)
then the output
"truth"
otherwise output
" False"
all
con
Task #5
Print the message "true" if the product of two negative numbers is greater than zero, otherwise print the message "false"
Solution:
alg
negative
start things
i, h, s, m
conclusion
"Enter two negative numbers"
input
i h
c:=0
m := i*h
if
m>s
then the conclusion is ns
, "true"
otherwise output ns
,"False"
all
con
Loop "for"
Task #1
Find Factorial natural numbern ( Factorial of a natural number n is the product of all natural numbers between 1 and n ) Solution:
alg
factorial
start things
a. b
whole
n, and
conclusion
input
n
a:= 1
nc for
and from
1 before
n
conclusion ns,
" enter the number"
input
b
a:= a * b
kts
conclusion ns,
"factorial",n,"of integers is", and
con
Task #2
Find the maximum value amongn - integers
Solution:
alg
maximum
start things
a, b
whole
i, n
conclusion
"Enter the number of integers to compare"
input
n
a:=0
nc for
and from 1 before
n
conclusion ns,
"enter the number"
input
b
if
b>a
then
a:=b
all
kts
conclusion ns,
"the maximum number among the data is a number", and
con
Task #3
Find amongn-integers number of negative
Solution:
alg
coincidence
start things
a, b, c
whole
n, i, s
conclusion "
enter the number of natural numbers"
input
n
conclusion ns,
"enter the number"
input
b
n:= n - 1
h:= 0
nc for
and from
1 before
n
conclusion ns,"
enter the number"
input
With
if
c = b
then
s:= s + 1
all
kts
conclusion ns,
con
Task #4
Sequentially entered n-integers. Find the number of matches with the first number
Solution:
start things
a, b, c
whole
n, i, s
conclusion
"Enter the number of natural numbers"
input
n
conclusion ns,
"enter the number"
input
b
n:= n - 1
h:= 0
nc for
and from
1 before n
conclusion ns,
" enter the number"
input
With
if
c = b
then s:= s + 1
all
kts
conclusion ns,
"the number of matches with the first number is", z
con
Task #5
Sequentially entered n-integers. Find the difference between the maximum and minimum values of given numbers
Solution:
alg
difference
start things
a. b, s, d
whole
n, and
conclusion
"Enter number of numbers"
input
n
a:= 0
c:=0
nc for
and from 1 before n
conclusion ns,
"enter the number"
input
d
if
e>s
then
c:=d
all
if
d<а
then
a:= d
all
kts b:= c - a
conclusion ns,
"the difference between the minimum and maximum values \u200b\u200bis equal", b
con
The while loop
Task #1
Find the sum of all numbers between 1 and 5
Solution:
alg
numbers
start things
a, b
conclusion
"Enter two numbers such that the second number is greater than the first"
input
a, b
nts bye
a<б
a:= a + 1
kts
conclusion ns
, a
con
Task #2
Given two numbers such that the second number is greater than the first. It is necessary to add 1 to the first number until it is equal to the second number, display it on the monitor.
Solution:
alg
sum
start things
a, b, c
conclusion
" enter summation interval"
input
a, b
c:= a
nts bye
a< б
a:= a + 1
c:= c + a
kts
conclusion ns
," the sum of the numbers on the given interval is", with
con
Task #3
You are given two arbitrary numbers. As long as their product is less than 100, increase each number by 2 and display the final numbers on the monitor
Solution:
alg
work
start things
a, b, c
conclusion
"Enter two random numbers"
input
a, b
c:= 100
nts bye
a*b< с
a:= a + 2
b := b + 2
kts
conclusion ns
, a, b
con
One-Dimensional Arrays
Task #1
Fill an array with random numbers and output its elements Solution:
alg
array 2
early target
n,i
thing
b, max
clothestab
a [ 1:n ]
conclusion
"fill array"
input
n
max:= 0
nc for
i from 1 before n
conclusion ns,
"enter array element"
input
b
if
b > max
then
max:=b
all
kts
conclusion ns,
con
Task #2
Find the maximum element of the array and display it on the monitor Solution:
alg
array 2
early
whole n,i
thing
b, max
clothestab
a [ 1:n ]
conclusion
"fill array"
input
n
max:= 0
nc for
i from 1 before n
conclusion ns,
"enter array element"
input
b
if
b > max
then
max:=b
all
kts
conclusion ns,
" the maximum element of this array is", max
con
Task #3
Find the sum of the elements of a one-dimensional array Solution:
alg
sum
early whole
n,i
clothestab
a [ 1:n ]
thing
b, z
conclusion
" enter the number of array elements "
input
n
z:= 0
nc for
i from 1 before n
conclusion ns,
"enter array element"
input
b
z:= z + b
kts
conclusion ns,
"sum",n,"array elements equals", z
con
Task #4
Find the product of the elements of a one-dimensional array Solution:
alg
work
early target
i, n
thing
s, d
clothestab
a [ 1:n ]
conclusion
"enter the number of array elements"
input
n
d:= 1
nc for
i from 1 before n
conclusion ns,
"enter the number"
input
s
d:= d*s
kts
conclusion ns,"
product", n, " elements equals", d
con
Arrays
Task #1
Fill the matrix with random numbers Solution:
alg
array is two dimensional
whole
n, j, h, v
start clothestab
a
conclusion
"enter the number of elements in the table"
input
n
h:= 0
v:= 0
conclusion ns,
"fill array"
input
a
nc for
j from 1 before n
if
a > 0
then
h:= h + 1
otherwise
v:= v + 1
kts
conclusion ns,
a
con
Task #2
Calculate the number of positive and negative elements of the first row of the matrix Solution:
alg
array 2
early
thing b, x, z
whole
i, n
conclusion
input
n x:=0
z:= 0
nc for
i from 1 before n
conclusion
ns," enter the number"
input
b
if
b > 0
then
x:= x + 1
otherwise
z:= z + 1
all
kts
conclusion ns,
conclusion ns,
con
Task #3
Calculate the sum of the elements of each row Solution:
alg
array 3
start things
b, x, z, y
whole
i, n
clothestab a[ 1:n, 1:n]
conclusion
"enter number of columns"
input
n x:=0
z:= 0
nc for
i from 1 before n
conclusion ns,
"fill array"
input
a[ 1:n, 1:n]
b:= a[ 1,i ]+a[ n, i ]
kts
conclusion ns,
"the number of positive numbers is",x
conclusion ns,
"the number of negative numbers is", z
con
Task #4
Calculate the sum of the three numbers in the second row of a three-by-three matrix Solution:
alg
matrix
early whole
i, n
clothestab
a[1:3, 1:3]
conclusion
"fill array"
input
a[1:3, 1:3]
n:=0
nc
for
i from 1 before 3
n:= n + a[ 2,i]
kts
conclusion ns,
"the sum of the numbers in the second row of the array is", n
con
Algorithm for drawing a spiral:
use Drawer
alg
early
. move to a point(3,3)
. lower the pen
. coil(1); coil(3); coil(5); coil(7); coil (9)
. raise the pen
con
alg turn(arg w)
early
. shift by vector(a, 0)
. shift by vector(0, -a)
. shift by vector(-a-1.0)
. shift by vector(0, a+1)
con
Pay attention to the command block:
Coil(1); coil(3); coil(5); coil(7); coil (9)
Auxiliary algorithm "coil (arg thing a)" is called 5 times, but it cannot be called in the "N times" loop, because each time it is called with different values argument.
But you can see that the values of the argument change from 1 to 9, each time increasing by 2. So, we can help loop with counter. Also, such a cycle is called the "for" cycle.
Loop with counter- a loop in which some variable changes its value from a given initial value to a final value with some step, and for each value of this variable, the body of the loop is executed once.
Typically, this loop is used if you need to iterate over some values and perform some actions for each of them.
General view of the cycle with a counter:
nc for<счетчик>from<нач. знач.>before<кон. знач.>[step<знач.>]
<тело цикла (последовательность команд)>
kts
It is not necessary to indicate the step, if it is not specified, then it is considered equal to one.
Now we can rewrite the "spiral" algorithm in this way:
use Drawer
alg
early
. move to a point(3,3)
. lower the pen
. whole size
. nc for size 1 to 9 step 2
. . coil(size)
. kts
. raise the pen
con
alg turn(arg w)
early
. shift by vector(a, 0)
. shift by vector(0, -a)
. shift by vector(-a-1.0)
. shift by vector(0, a+1)
con
In this example, the counter variable "size" will receive the values: 1, 3, 5, 7, 9. That is, loop will be executed 5 times. For each value of the “size” variable, the loop body will be executed once, in our example, this is a call to the auxiliary algorithm “coil (arg thing)”.
Before the first use of a variable, it must be declared, i.e., what type it is. This is done in our program in the line “integer size”, i.e. we indicate that we will use the “size” variable to store integers, and therefore we need to allocate memory for it. We will talk more about variables a little later.
The block diagram of such an algorithm looks like this:
Let's look at another example:
Let's first remember and write an auxiliary algorithm that will draw a square at the point (x, y). For a change for drawing, we will use the command shift by vector(in the previous examples, they were shifted to a point).
The algorithm could be like this:
alg square(arg x, y, side)
early
. move to a point(x, y)
. shift by vector(-side/2, side/2)
. lower the pen
. shift by vector(side, 0)
. shift by vector(0, -side)
. shift by vector(-side, 0)
. shift by vector(0, side)
. raise the pen
con
Using such an auxiliary algorithm, we draw the following figure:
To do this, we use the "for" loop. Study the sample program:
use Drawer
alg figure1
early
. integer z
. nc for z from 2 to 10 step 2
. . square(0, 0, z)
. kts
con
alg square(arg x, y, side)
early
. move to a point(x, y)
. shift by vector(-side/2, side/2)
. lower the pen
. shift by vector(side, 0)
. shift by vector(0, -side)
. shift by vector(-side, 0)
. shift by vector(0, side)
. raise the pen
con
In this example, the variable "z" will receive the values: 2, 4, 6, 8, 10. That is, loop will be executed 5 times. For each “z” value, the loop body will be executed once, in our example, this is a call to the auxiliary square algorithm.
Before the first use of a variable, it must be declared, i.e., what type it is. This is done in our program in the line "integer z", i.e. we indicate that we will use the variable "z" to store integers, and therefore we need to allocate memory for it. We will talk more about variables a little later.
As you noticed, the algorithm used not only numbers, but also algebraic expressions, formulas, for example "-side/2". In computer science, these expressions are called arithmetic. The rules of the language allow, when writing algorithms, wherever you can write a number, write an arbitrary arithmetic expression.
Consider the problem:
The input to the program is a natural number not exceeding 2 * 10 9 . Determine the sum of the digits of this number.
At first glance, the task is quite simple: you need to consistently select the numbers in the number and add them to the sum. At the same time, it is obvious that the number of digits in the number can change, so the final value of the cycle parameter for turns out to be undefined and there are difficulties with its application.
AT cyclic algorithms where the number of repetitions of a particular set of instructions cannot be obtained before the start of the instruction set, conditional loops are used.
The while loop
One of such constructions in the Kumir programming language is cycle bye. This cycle, often referred to as loop with precondition, has the following format:
- nc bye condition
- loop_body
The condition written after official word while , is a boolean expression.
The loop is executed as follows:
- The value of the logical expression is evaluated.
- If the result of the calculation is no , then the loop ends and Kumir moves to the first command after the while loop. If the result of the calculation is yes, then the body of the loop is executed, after which the value of the expression is again calculated with a new value.
Important! In the body of the loop, some value associated with the condition must still change in order to ensure the end of the loop, otherwise, the loop may be eternal.
Now let's use the while loop to solve our problem.
- input num
- nc while num > 0
- sum:= sum + mod(num, 10 )
- num:= div(num, 10 )
- withdrawal amount
So, during each execution of the loop body, the last digit of the number is added to the amount, then the number is reduced by 10 times. Obviously, eventually num will become equal to 0, after which the loop will end.
Until then cycle
In Idol, there is another variant of a conditional loop, called the until loop, which has the following format:
- loop_body
- kc under condition
If in the loop while the condition is checked before the body of the loop, then in the loop until then - after. Therefore, this cycle is often called loop with postcondition. The body of such a loop will always be executed at least once.
The work of the loop until then proceeds as follows:
- Loop body is executed
- The value of the logical expression is evaluated. If the result of the calculation is no , then the body of the loop begins to be executed again, and so on. If the result of the calculation is yes , then the loop ends, and Kumir proceeds to the execution of the next command after the loop.
A task. The input to the program is a sequence of integers ending in zero. Find the number of negative numbers in the sequence. It is guaranteed that the sequence contains at least one non-zero number.
(Program code snippet)
- input num
- if num 0
- then k:= k + 1
- kts at num = 0
- output k