Cyclic algorithm ICT pascal example. Cyclic algorithms Types of cycles and cyclic commands in Pascal. The choice of cycle depends on the characteristics of the problem conditions. Only practice will tell you the optimal solution


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 (service word to ), and in reverse order (functional 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.







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 to achieve the result specific sequence actions are performed several times. 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

1st form of writing the For operator in general view 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 consider the algorithm of the Repeat loop: The body of the loop located between the reserved words Repeat and Until is executed. 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























Back forward

Attention! Preview The slides are for informational purposes only and may not represent all the features of the presentation. If you are interested this work, please download the full version.

Target: studying the algorithmic structure of cycles, creating models and algorithms for solving practical problems.

During the classes

I. Updating knowledge

  • Review the concept of an algorithm and the basic constructs of an algorithmic language.
  • Be able to develop mathematical model, algorithm and block diagram for solving the problem.
  • Have an understanding of programming languages ​​and their purposes.
  • Be able to work in a programming environment.
  • Know program structures.
  • Be able to write expressions containing numerical and symbolic quantities.
  • Know the structures of operators and the features of their work.
  • Be able to use operators when writing programs with linear and branching structures.
  • Be able to create and run programs on a computer for debugging.

II. Theoretical material of the lesson

Most practical problems require repeated repetition of the same actions, that is, reuse of one or more operators. (Presentation)

Suppose you need to enter and process a sequence of numbers. If there are only five numbers, you can create a linear algorithm. If there are a thousand of them, it is possible to write a linear algorithm, but it is very tedious and irrational. If the number of numbers is unknown at the time the algorithm is developed, then a linear algorithm is fundamentally impossible.

Another example. To find a person's last name on the list, you need to check the first last name on the list, then the second, third, etc. until the desired one is found or the end of the list is reached. You can overcome such difficulties with the help of cycles.

A cycle is a section of an algorithm (program) that is executed repeatedly. Accordingly, a cyclic algorithm is an algorithm containing cycles.

There are two types of cycles: with a known number of repetitions and with an unknown number of repetitions. In both cases, this refers to the number of repetitions at the algorithm development stage.

There are 3 types of cyclic structures:

  • Loop with precondition;
  • Loop with postcondition;
  • Loop with parameter;

Otherwise, these structures are called cycles like “While”, “Before”, “For”.

Graphic form of recording data of algorithmic structures:

Loop with precondition (aka loop Bye) has the form:

condition – expression of logical type.

The loop may not be executed even once if the value of the logical expression immediately turns out to be false.

The series of commands between begin and end are executed until while the condition is true .

For that for the cycle to end, it is necessary that the sequence of instructions between BEGIN and END changes the value of the variables included in condition.

Loop with postcondition (aka loop before) has the form:

condition – expression of logical type.

Note:

Sequence of instructions betweenrepeat Anduntil will always be fulfilled at least once;

In order for the loop to complete, it is necessary that the sequence of statements betweenrepeat Anduntil changed the values ​​of the variables included in the condition expression.

The repeat instruction, like the while instruction, is used in a program if it is necessary to carry out some repeated calculations (a loop), but the number of repetitions is not known in advance and is determined by the progress of the calculation itself.

Loop with a parameter (aka loop For) has the form:

i – cycle parameter;
a – initial value of the cycle;
b – final value of the cycle;
h – parameter change step.

The structure of this cycle is otherwise called cycle i times.

This command is executed in this way: the parameter i is set to the initial value a, compared with the final value b, and if it is less than or equal to the final value b, a series of commands is executed. The parameter is assigned the value of the previous one, increased by h– step of parameter change and is again compared with the final value b.

In the Pascal programming language, the parameter change step can be equal to one or minus one.

If there is only one statement between begin and end, then operator brackets do not need to be written. This rule works for loops like “While” and “For”.

Let's look at an example of solving problems using these structures

Example.

Calculate the product of numbers from 1 to 5 using various loop options

Mathematical model:

Р= 1·2·3·4·5=120

Let's compose the algorithm in the form of a block diagram.

To check the correctness of the algorithm, let's fill in the trace table.

Step Operation R i Condition check
1 P:=1 1
2 i:=1; 1 1
3 i<=5
P:=P*I
i:=i+1
1 1 1<=5, да (истина)
4 i<=5
P:=P*I
i:=i+1
2 2 2<=5, да (истина)
5 i<=5
P:=P*I
i:=i+1
6 3 3<=5, да (истина)
6 i<=5
P:=P*I
i:=i+1
24 4 4<=5, да (истина)
7 i<=5
P:=P*I
i:=i+1
120 5 5<=5, да (истина)
8 i<=5
P:=P*I
i:=i+1
6<=5, нет (ложь)

Checking a condition occurs in several steps: checking the condition and executing commands on one of the branches. Therefore, the trace table does not record algorithm commands, but individual operations performed by the computer at each step.

Step one: P is assigned a value of one.

Step two: i is assigned the value one.

Step three: when i is equal to one, we check the condition one is less than or equal to five, yes, the condition is true, which means P is assigned the value one multiplied by one, there will be two. For i: one plus one equals two.

Step four: when i is equal to two, we check the condition two is less than or equal to five, yes, the condition is true, which means P is assigned the value 2 times one, it will be 2. For i: two plus one, it will be three.

Step five: with i equal to three, we check the condition three is less than or equal to five, yes, the condition is true, which means P is assigned the value of two multiplied by three, it will be six. For i: three plus one equals four.

Step six: with i equal to four, we check the condition four is less than or equal to five, yes, the condition is true, which means P is assigned the value of six times four, it will be twenty-four. For i: four plus one equals five.

Step seven: with i equal to five, we check the condition five is less than or equal to five, yes, the condition is true, which means P is assigned the value of twenty-four multiplied by five, it will be one hundred and twenty. For i: five plus one is six.

Step eight: when i is equal to six, we check the condition six is ​​less than or equal to five, no, the condition is false, then we exit the loop, and as a result we get the last value equal to one hundred and twenty.

Program Pr1;
Var i: integer;
Begin
P:=1;
i:=1;
While i<=5 do
begin
P:=P*i;
i:=i+1;
end;
Write('P=', P);
end.

For a loop with a postcondition, we will build a block diagram and a trace table. (slide16)

As a result, we get the last value equal to one hundred and twenty at the seventh step

And for the Cycle with a parameter we will build a block diagram and a trace table. (slide 17)

As a result, we get the last value equal to one hundred twenty at the sixth step

Task:

Display numbers from 1 to 5 in:

  1. direct order;
  2. in reverse order.

Mathematical model:

  1. 1 2 3 4 5;
  2. 5 4 3 2 1.

The block diagram and program for solving the problem are presented for numbers in forward and reverse order.

(slide 21)

Let us write the considered algorithms in the Pascal programming language.

(slide 22)

III. Summing up the lesson

And so we considered the following questions:

  1. Algorithmic structure cycle;
  2. Types of algorithmic structures:
    1. Loop with precondition;
    2. Loop with postcondition;
    3. Loop with parameter;
  3. We looked at ways to record these structures;
  4. We looked at examples of solving problems using these structures.