Cyclic algorithms04/06/2017
Cyclic algorithms
Types of cycles and cyclic
Pascal commands

A cycle is multiple
repetition of sequence
actions
Repetitive part of the algorithm
called the BODY OF THE LOOP
Types of cycles
With a given number
repetitions
Fulfillment condition
cycle
With condition
Exit condition
cycle

Types of cycles (contents)
Loop with precondition
Practice
Loop with postcondition
Practice
Loop with parameters
Practice
Solving complex problems

Loop with precondition

Practice

condition, and the action that must be performed only
After checking the conditions, use a loop in the precondition.


Before each execution of the loop body, a check occurs
conditions, if the result is “true”, then the body of the loop is executed
Once again, if “false”, then the loop exits.
On the block diagram
Start of the cycle
No
Condition
YES
Loop Body
End of the cycle
In Pascal
While<условие>do
begin
<тело цикла>
end;

Loop with postcondition

Practice
If the number of repetitions is unknown in advance, but only given
condition, and the action that must be performed before
Condition tests use a loop with a postcondition.
A logical expression is used as a condition, body
loop – simple or compound operator.
After each execution of the loop body, a check occurs
conditions, if the result is false, then the body of the loop is executed
Once again, if “true”, then the loop exits.
On the block diagram
In Pascal
Repeat
Loop Body
<тело цикла>
Yes
No
Condition
Until<условие>;

Loop with parameter

Practice
Loop with parameter
In cases where the number of repetitions is known in advance
a loop is applied in the parameter.
The variable that specifies the number of repetitions is called
loop parameter or control variable.
After each execution of the loop body, the control
variable increases or decreases, loop
is executed until it exceeds either
there will be less restriction.
On the block diagram
In Pascal
For X:=A to B do
X:=A,B,C
Loop Body
X – control variable (cycle parameter)
A – initial value of X, B – final value of X
C – change step X
Begin
<тело цикла>
End;
As a step you can use
only:
"to" = 1;
"downto" = -1

Example task using a loop with a precondition
Theory

Verbal algorithm:
Multiply the number X initially equal to 1
a given number of times (N) by 3.
Start
ProgrammStep;
Var
H,B,X:integer;
Begin
Writeln('Degree?');
Readln(H);
X:=1;
B:=1;
While B<=H do
Begin
X:=X*3;
B:=B+1;
End;
Writeln('Result',X);
End.
Pascal
N
Entering the desired degree
X:=1
Initial values
B:=1
No
"B" degree counter
B≤H
Yes
X:=X*3
Multiply by 3
B=B+1
Counter increase
X
Output of the resulting
values
end
Block Diagram
Explanations

Example of a task using a loop with a postcondition
Theory
TASK: Raise the number 3 to a given power
Verbal algorithm:

ProgrammStep;
Var
H,B,X:integer;
Begin
Writeln('Degree?');
Readln(H);
X:=1;
B:=0;
Repeat
X:=X*3;
B:=B+1;
No
Until B>=H;
Writeln('Result',X);
End.
Start
N
Entering the desired degree
X:=1
Initial values
B:=0
Multiply by 3
X:=X*3
Counter increase
B=B+1
Yes
B>=H
"B" degree counter
X
Output of the resulting
values
end
Pascal
Block Diagram
Explanations

Example task using a loop with a parameter
Theory
TASK: Raise the number 3 to a given power
Verbal algorithm:
Multiply the number X, initially equal to 1, a specified number of times (H) by 3.
ProgrammStep;
Var
H,B,X:integer;
Begin
Writeln('Degree?');
Readln(H);
X:=1;
For B:=1 to H do
Begin
X:=X*3;
End;
Writeln('Result',X);
End.
Pascal
Start
N
X:=1
B:=1,H,1
X:=X*3
X
end
Block Diagram
Entering the desired degree
Initial value X=1
Parameters from 1 to H
Multiply by 3
Output of the resulting
values
Explanations

The choice of cycle depends on the characteristics of the problem conditions. Only practice will tell you the optimal solution.

Task: Having started training, the athlete on the first day
ran 10 km. Every day he increased the daily
the norm is 10% of the norm of the previous day.
What is the total distance the athlete will cover in 7 days?
Input variables:
d – number of days
Sd – distance for the current day
Output variables:
S – common path

Block - diagram for the solution

Start
S:=10
Sd:=10
d:=1
d:=d+1
Sd:=Sd*1.1
S:=S+Sd
No
D=7
Yes
s
end

Program in Pascal

Cycle "For"
Cycle "Bye"
Cycle "Before"
Program beg;
Program beg;
Program beg;
Var
Var
Var
S,Sd: real;
S,Sd: real;
S,Sd: real;
d:byte;
d:byte;
d:byte;
Begin
Begin
Begin
S:=10;
S:=10;
S:=10;
Sd:=10;
Sd:=10;
Sd:=10;
For d:=2 to 7 do
begin
While d<7 do
begin
Repeat
d:=d+1;
Sd:=1.1*Sd;
d:=d+1;
Sd:=1.1*Sd;
S:=S+Sd;
Sd:=1.1*Sd;
S:=S+Sd;
end;
S:=S+Sd;
until (d=7);
Writeln(‘S=‘,S);
end;
Writeln(‘S=‘,S);
End.
Writeln(‘S=‘,S);
End.
End.

Questions for control:
1. Which operator in Pascal defines a loop with
precondition
2. How to specify the step “1” and “-1” as parameters in a loop
3. Which branch does the loop exit from?
postcondition
4. Are there conditions in a loop with a parameter?
5. What can be the body of a loop
6. When using a loop with parameters
End

Slide 1

Performer ROBOT Cyclic algorithm
Presentation for a computer science lesson. Grade 9 Topic: Control and algorithms

Slide 2

FOR i:=1 TO N DO BEGIN action1; action2; END;
FOR i:=1 TO N DO action1; action2;
1

Slide 3

2
WHILE (CONDITION IS TRUE) DO BEGIN action1; action2; END;
WHILE (CONDITION IS TRUE) DO action1; action2;

Slide 4

3
17 cells
12 cells

Slide 5

4
Program N1; var i:integer; Begin For i:=1 to 12 do RobotForw; RobotLeft; For i:=1 to 17 do RobotForw; RobotLeft; For i:=1 to 12 do RobotForw; RobotLeft; For i:=1 to 17 do RobotForw; RobotLeft; end.
Moving down
Moving to the right
Moving up
Moving left
This and the next commands turn the robot to the left in the corner

Slide 6

5
If you put a wall, the robot will crash into it and the program will stop

Slide 7

6
Program N2; var i:integer; Begin While FreeForw do RobotForw; RobotLeft; While FreeForw do RobotForw; RobotLeft; While FreeForw do RobotForw; RobotLeft; While FreeForw do RobotForw; RobotLeft; end.
While there is free space ahead, move the robot forward.

Slide 8

Slide 9

8
Program N3; var i:integer; Begin for i:=1 to 4 do begin While FreeForw do RobotForw; RobotLeft; end; end.
Move forward four times until there is an obstacle and turn left

Slide 10

9
Move forward four times until there is an obstacle and turn left

Slide 11

10
Tasks for independent work
Task 1. An obstacle is placed at the left wall of the setting in a random place. The robot must reach point 1 and return to its original state. Note: use three series-connected loops BYE
1
1

Slide 12

11
Task 2. A weight is placed at the left wall of the setting in an arbitrary place. The robot must reach the cargo, take it, transport it to the warehouse and return to its original state. Note: use two series-connected loops BYE

Slide 13

12
Task 3. Five weights are placed at the left wall of the setting in a random place. The robot must transport all the goods to the warehouse. Note: use two sequentially connected WHILE loops nested in a loop with a parameter.

Slide 14

13
Example 1 The robot is located in front of the entrance to the corridor. You need to mark all the cells inside the corridor and go back

Slide 15

14
Program N7; Begin RobotForw; While not FreeLeft do begin Select; RobotForw; end; RobotBack; While not FreeLeft do RobotBack; end.
Taking a step forward to enter the tunnel
While there is a wall on the left, mark the cell and take a step forward
We return back to the tunnel
While there is a wall on the left, we are moving one step back

Slide 16

15
Example 2 There are two walls placed at an angle. The lengths of the walls are arbitrary. The robot is located in the corner between the walls (see picture). It is necessary to create a program in which the robot marks all the cells on the inside of the wall. The final position of the robot is arbitrary.

Slide 17

16
Program N8; Begin While not FreeRight do begin Select; RobotForw; end; While FreeBack do RobotBack; RobotLeft; While not FreeLeft do begin Select; RobotForw; end; end.
While there is no space on the right, mark the box and take a step forward.
Bringing the robot back
Turn left
While there is no space on the left, mark the box and take a step forward.

Slide 18

Slide 19

18
Example 3 The furnishings are blocked by a wall, dividing the furnishings into two parts. There is a cage-sized passage in the wall in a random location. It is necessary to create a program in which the robot finds this passage and moves to another part of the environment.

Slide 20

19
Program N9; Begin RobotLeft; While FreeForw do RobotForw; RobotRight; While not FreeLeft do RobotForw; RobotLeft; RobotForw; RobotForw; end.
We turn the robot towards the wall.
Let's move forward until we hit the wall
Rotate the robot along the wall
We move forward until the wall ends
Turn the robot towards the passage
We take two steps forward, we pass to the other half of the situation






Loop with a precondition If the number of repetitions is unknown in advance, but is specified only by a condition, and an action that must be performed only after checking the conditions, use a loop with a precondition. A logical expression is used as a condition, the body of the loop is a simple or compound operator. Before each execution of the loop body, the condition is checked, if the result is “true”, then the loop body is executed again, if “false”, then the loop is exited. On the block diagram In Pascal begin end; Condition Body of the loop No Practice Start of the loop End of the loop YES While do


Loop with a postcondition If the number of repetitions is unknown in advance, but is specified only by a condition, and the action that must be performed before checking the condition, use a loop with a postcondition. A logical expression is used as a condition, the body of the loop is a simple or compound operator. After each execution of the loop body, the condition is checked, if the result is “false”, then the loop body is executed again, if “true”, then the loop is exited. On the block diagram In Pascal Repeat Condition Loop Body Yes No Practice Until ;


Loop with a parameter In cases where the number of repetitions is known in advance, a loop with a parameter is used. The variable that specifies the number of repetitions is called a loop parameter or control variable. After each execution of the loop body, the control variable is increased or decreased, the loop is executed until it exceeds or becomes less than the limit. In the block diagram in Pascal, X is the control variable (cycle parameter) A is the initial value of X, B is the final value of X C is the step of changing X. As a step you can only use: “to” = 1; “downto” = -1 X:=A,B,C Loop Body Practice For X:=A to B do Begin End;


An example of a problem using a loop with a precondition Raise the number 3 to a given power TASK: Verbal algorithm: Multiply the number X, initially equal to 1, a given number of times (H) by 3. start H BHBH X:=1 X:=X*3 end X Enter the given degrees Initial values ​​“B” degree counter B=B+1 Multiplying by 3 Increasing the counter Outputting the resulting value Programm Stepen; Var H,B,X:integer; Begin Writeln(Degree?); Readln(H); X:=1; B:=1; While B


H X:=1 X:=X*3 end X Enter a given power Initial values" title="Example of a task using a loop with a postcondition Raise the number 3 to a given power TASK: Verbal algorithm: Multiply the number X initially equal to 1 given number of times (H) for 3. start N B>=H X:=1 X:=X*3 end X Enter a given degree Initial values" class="link_thumb"> 8 !} An example of a problem using a loop with a postcondition Raise the number 3 to a given power TASK: Verbal algorithm: Multiply the number X, initially equal to 1, a specified number of times (H) by 3. start H B>=H X:=1 X:=X*3 end X Entering a given degree Initial values ​​“B” degree counter B=B+1 Multiplying by 3 Increasing the counter Outputting the resulting value Programm Stepen; Var H,B,X:integer; Begin Writeln(Degree?); Readln(H); X:=1; B:=0; Repeat X:=X*3; B:=B+1; Until B>=H; Writeln(Result,X); End. No Yes Pascal Theory Block Diagram Explanations B:=0 =H X:=1 X:=X*3 end X Entering a given degree Initial values"> =H X:=1 X:=X*3 end X Entering a given degree Initial values ​​"B" degree counter B=B+1 Multiplying by 3 Increase the counter Output the resulting value Programm Stepen; Var H,B,X:integer; Begin Writeln(Degree?); Readln(H); X:=1; B:=0; Repeat X:=X*3; B: =B+1; Until B>=H; Writeln (Result,X); End. No Yes Theory Pascal Block Diagram Explanations B:=0"> =H X:=1 X:=X*3 end X Enter a given degree Initial values" title=" Example of a problem using a loop with a postcondition Raise the number 3 to a given power TASK: Verbal algorithm: Multiply the number X initially equal to 1 a given number of times (H) by 3. beginning N B>=H X: =1 X:=X*3 end X Entering the specified degree Initial values"> title="An example of a problem using a loop with a postcondition Raise the number 3 to a given power TASK: Verbal algorithm: Multiply the number X, initially equal to 1, a specified number of times (H) by 3. start H B>=H X:=1 X:=X*3 end X Entering a given degree Initial values"> !}


An example of a task using a loop with the parameter Raise the number 3 to a given power TASK: Verbal algorithm: Multiply the number X, initially equal to 1, a specified number of times (H) by 3. start H X:=1 X:=X*3 end X Enter a given power Initial value X=1 Parameters from 1 to N Multiplication by 3 Output of the resulting value Programm Stepen; Var H,B,X:integer; Begin Writeln(Degree?); Readln(H); X:=1; For B:=1 to H do Begin X:=X*3; End; Writeln(Result,X); End. B:=1,H,1 Pascal Theory Block Diagram Explanations




Task: Having started training, the athlete ran 10 km on the first day. Every day he increased the daily norm by 10% of the previous day's norm. What is the total distance the athlete will cover in 7 days? Input variables: Output variables: S – total path d – number of days Sd – distance for the current day


End Questions for control: 1. Which operator in Pascal defines a loop with a precondition 2. How to specify the step “1” and “-1” in a parameter in a loop 3. Which branch does the loop with a postcondition follow? 4. Is there a condition parameter 5. What can be the body of a loop 6. When is a loop with parameters used

Slide 2

Plan

Concept of a loop Loop statement For Loop While Loop Repeat Literature

Slide 3

Literature

Kastornov A.F., Evstratova G.A. Pascal programming language: tutorial for universities. - Cherepovets: State Educational Institution of Higher Professional Education ChSU, 2010. - 117 p. - Bibliography: P.114. Electronic textbook on the Pascal programming language /http://pascal.guti.ru Plan

Slide 4

The concept of a cycle

Algorithms for solving many problems are cyclic, in which a certain sequence of actions is performed several times to achieve a result. For example, a knowledge control program displays a question, accepts the answer, adds a mark for the answer to the total score, then repeats these actions until the subject answers all the questions. Or, for example, to search for the desired surname in the list, you should check the first surname in the list to see if it matches the searched one, then the second, third, etc. until the desired surname is found or the end of the list is reached.

Slide 5

An algorithm in which there is a group of statements that is executed several times is called cyclic. The group of repeated statements is called the body of the loop. In Pascal, loops can be implemented using the For, While, and Repeat loop statements. Plan

Slide 6

For loop operator

The For loop operator is used if the body of the loop needs to be executed several times, and the number of repetitions is known in advance.

Slide 7

1st form of writing the For loop operator

The 1st form of writing the For operator in general looks like this: ForCounter:=Start_valuetoFinal_valuedoOperator; Where For, to, do are function words. A counter is an ordinal variable (usually an Integer) that determines the number of times the loop will repeat. The number of repetitions is calculated using the formula: Final_value – Initial_value+1. End_Value must be greater than or equal to Start_Value.

Slide 8

If the body of the loop consists of several operators, then the 1st form of writing the For operator looks like this: ForCounter:=Start_valuetoFinal_valuedo Begin (Loop body) End;

Slide 9

Let's look at the algorithm for the For loop in the first form of writing. The counter is assigned an Initial_ value. The condition is checked: Is the counter value greater than the End_value? If the condition is true (Yes), the loop ends. If the condition is false (No), then the body of the loop is executed, then the counter value is increased by one and the condition is checked again, i.e. clause 2.

Slide 10

2nd form of writing the For loop operator

The 2nd form of writing the For operator in general looks like this: For Counter:=Start_valuedowntoFinal_valuedoOperator; Where: For, downto, do are function words. A counter is an ordinal variable (usually an Integer) that determines the number of times the loop will repeat. The number of repetitions is calculated using the formula: Start_value–Final_value+1. Start_Value must be greater than or equal to End_Value.

Slide 11

If the body of the loop consists of several operators, then the 2nd form of writing the For operator looks like this: ForCounter:=Start_valuedowntoFinal_valuedo Begin //Loop body End;

Slide 12

Let's consider the algorithm of the For loop in the second form of notation: The counter is assigned an Initial_ value. The condition is checked: Is the counter value less than the End_value? If the condition is true (Yes), the loop ends. If the condition is false (No), then the body of the loop is executed, then the counter value is decreased by one and the condition is checked again, i.e. clause 2.

Slide 13

For loop operator

programEx1; var i, n:integer; (i – counter, n – required number of stars) s:string;(s – generated string of stars) begin Writeln("Enter the number of stars"); (queries the number of stars) Readln(n); (the user enters the number of stars n) s:=""; (formation of a string of asterisks begins with an empty string) (The string is formed using a For loop. The initial_value of the counter is 1, The final_value is the required number of stars n.) fori:= 1 to n do s:=s+"*"; (at each step of the loop one asterisk is glued to the line) Writeln(s); (a line is printed) Readln; end. Plan Example: The program generates a string of stars. The number of stars in a line is determined by the user.

Slide 14

While Loop

The While loop is used when the number of repetitions of the loop body during program development is unknown and can only be determined while the program is running. In general, the While statement is written as follows: While Condition doOperator; Where While, do are function words. Condition is a logical expression that determines the continuation of the loop.

Slide 15

If the body of the loop consists of several statements, then the While loop is written as follows: WhileCondition do Begin //Loop body End;

Slide 16

Let's look at the algorithm for the While loop: The condition is checked. If the condition is true, then the body of the loop is executed. After which the condition is checked again. If the condition is false, then the loop ends.

Slide 17

Thus, While is a loop with a precondition or a “While” loop (the body of the loop is executed while the condition is true). If on the first pass of the loop the condition is false, then the body of the loop will not be executed even once. If the condition never becomes false, then the loop will repeat indefinitely, i.e. looping will occur.

Slide 18

ProgramEx2; varAccount: Real; (account size) Month: Integer; (number of months that have passed since the account was opened) begin Account:=1000; (1000 rubles were deposited into the account) Month:=0; (account has just been opened) whileAccount

Slide 19

Repeat cycle

The Repeat loop, like the While loop, is used in a program if it is necessary to execute the body of the loop several times, but the number of repetitions is unknown in advance. In general, a Repeat loop is written as follows: Repeat //Body of the loop Until Condition; Where Repeat, Until are function words. Condition is a Boolean expression that determines the end of the loop.

Slide 20

Let's look at the algorithm for the Repeat loop: Executes what is between reserved words Repeat and Until loop body. The condition is checked. If the condition is true, the loop ends. If the condition is false, the body of the loop is executed again.

Slide 21

Thus, Repet is a loop with a postcondition or a “Before” loop (the body of the loop is executed until the condition is true). Therefore, the body of the loop is executed at least once. If the condition never becomes true, then the loop will become infinite.

Slide 22

ProgramEx3; var Time:integer; (division time) Cells: integer;(number of cells) begin Time:=0;(cell has not yet begun division) Cells:=1;(one cell) Repeat Time:=Time+3;(in the next three hours) Cells: =Cells*2;(the number of cells increased by 2 times) Until Cells>24; (until the condition “the number of cells is greater than 24” is true) Writeln(Time); (output the result) Readln; end. Plan Example: A single-celled amoeba divides into 2 cells every 3 hours. Determine how many hours later the number of cells will exceed 24.

View all slides


Types of cycles

loops with parameter for

loops with precondition

cycle while with precondition

cycle repeat - until with postcondition


Loop with precondition in Pascal - WHILE

A loop operator with a precondition performs actions an unknown number of times. The loop exits if some logical expression or its result turns out to be false.

Because loyalty logical expression is checked at the beginning, the body of the loop may not be executed even once.


Loop structure WHILE


Block - cycle diagram WHILE

operator

condition


Example

Task: Write a program that calculates the sum of all even numbers up to 50.

writeln("The sum is: ",sum);


Task

Write a program that searches for n!.


Loop with postcondition in Pascal – REPEAT-UNTIL

This operator is similar to the loop operator with a precondition, but differs from it in that the condition is checked after the body (actions) of the loop are executed. This ensures that it is executed at least once, unlike previously parsed loops.

Please note that this operator cycle implies the presence of several operators in the body of the cycle, that is, several actions can be performed, so the service words Begin And End Not needed.


Loop structure

REPEAT-UNTIL


Block - cycle diagram REPEAT-UNTIL

operator

condition


Example

Task: Write a program that determines the sum of the first and last digits in a number.

a,b,c,d:integer;

writeln("enter a number");

writeln(‘The sum of the first and last digit is:‘c);


Task

Write a program that determines whether a number is prime.


Loop with a parameter in Pascal - FOR

Cycle FOR sets the condition under which the program will work before it is executed, let’s say you need to loop the program n times, then this can be easily done using this loop.

U cycle FOR There is a characteristic feature - a counter, which is usually designated by the letter i or j.

In a loop, the counter can be specified either directly ( function word to ), and in reverse order(service word downto ).


Loop structure FOR

FOR i:= n1 TO n2 DO

1st recording form

FOR i:= n2 DOWNTO n1 DO

2nd recording form


Block - cycle diagram FOR

i:= n1 … n2

Loop Body


Example

Task: Write a program that calculates the nth power of a given number.

a, n, i, pr: integer;

writeln('Enter a number');

writeln('Enter the power of the number');

for i:= 1 to n do

writeln('The power of the number is',pr);


Task

Write a program that finds the number P = (1-1/2)(1-1/3)*…*(1-1/n).

N is entered from the keyboard.