Target: give the concept of cycles with a parameter, block diagrams depicting such cycles. Learn to draw up block diagrams and programs with loops using specific examples; give an idea of ​​the differences between loops with a precondition, a postcondition and a loop with a parameter; teach how to use different loops in one program if the program contains several loops; enter and execute programs using BPW or Turbo Pascal compilers.

1. Operator loop for ... to ... do ...

Sometimes you know in advance how many times the loop should be executed. For problems of this type, the Pascal language has operators loops with parameters .
The format for recording such operators is as follows:
for<cycle par.> := <initial value> to<final value.> do <operator>.
Here for, to, do- reserved words (for, to, perform);
<steam. cycle> - loop parameter - a variable of type integer (more precisely, any ordinal type);
<beginning value.> - initial value - a number or expression of the same type;
<con. value.> - final value - a number or expression of the same type;
<operator> is an arbitrary Pascal operator.
If there are several operators, then, as in the operator while... do ..., are used operator brackets: begin ... end.
For example, the following loop operator entries are possible:

for i:=a to b do s1;

for j:=a to b do begin s1; s2; ..., sn end; or

for k:=p to m do
begin
s1;
s2;
...
sn
end;

Here s1, s2, s3, ... sn are loop operators.
When executing the statement for first the expression is evaluated<initial value.> and assigning its value to the loop variable
<cycle par.> := <beginning value.>.
After this they repeat cyclically:
1) checking the condition<cycle par.> <con. value.>; if the condition is not met, the operator for finishes work;
2) execution of the statement<operator> or operators s1; s2; s3; ...sn;
3) loop variable<steam. cycle> increases by one.

We must immediately notice that it is impossible to set a loop step other than 1 in this statement.


Graphic representation of cycles for will be like this (see Fig. 33):

Rice. 33

Here: i is a loop variable; n is its initial value; k is its final value. The body of the cycle consists of an operator or several operators: s1; s2; ... sn;, which are drawn in a rectangle.

To illustrate the operator's work for Let's consider an example that has already become traditional when studying the work of this operator.

Example 1. Create a program for calculating the factorial of the number n, i.e. n!.

Let us recall from mathematics that the factorial of the number n is equal to the product of the numbers from 1 to n.
For example:

Z note . In mathematics it is accepted: 0! = 1.


Block diagram


Rice. 34

Program

Program Problem1; ( Calculating the factorial of n! )
uses WinCrt;
var
n, f, i: longint;
begin

f:= 1;
if n<> 0 then for i:= 1 to n do f:= f*i;
end.

Variable n - for a number entered by the user, the factorial of which must be found; f is the variable that will contain " accumulate" the value of the factorial of the number n; i is a loop variable.
The initial value of the variable f:= 1 is set.
Then the cycle begins. The variable i is assigned the initial value 1; it is compared with the final one - n (1<= n), If the condition is true, Then The operator is executed (there is only one in this program): f:= f*i, 1*1=1; the value of the loop variable is increased by 1, i.e. it becomes equal to: i:= i + 1, 1 + 1 = 2 and the loop repeats.
When the value of i will become equal to n, Then the loop will execute one last time because the next value of i will be n + 1, which is greater than the final value of n, condition i<= n - false, the loop is not executed.

2. Loop operator for...downto...do...

There is another form of the loop operator for:
for<par.cycle.> := <beginning zn.> downto <con. zn.> do <operator>.

Replacing a reserved word to on downto means that loop parameter step is (-1).

The parameter value changes from a larger value to a smaller one, i.e.
<beginning value.> <con. value.>.
A program for calculating the factorial of a number can be written using this loop operator.
Program

Program Problem1a;
uses WinCrt;
var
n, i, f: longint;
begin
write("Enter a natural number"); readln(n);
f:= 1;
if n<> 0 then for i:=n downto 1 do f:= f*i;
writeln("The factorial of ", n, " is ", f)
end.

1. Change the program so that it displays not a table of squares of numbers from 1 to n, but the square of only one number n, entered by the user.

2. Change and expand the program so that it gives the value of the square of the number and those odd numbers whose sum is equal.

3 . Continuing the topic of raising natural numbers to powers, without multiplication operations, let's consider two more interesting examples. In the first of them we will have to combine, " invest"two cycles into each other for, and in the second, cycles for And repeat.

Example 3. The cube of any natural number n is equal to the sum of n odd numbers following in order the numbers whose sum was the cube of the previous number n - 1:

13 = 1
23 = 3 + 5
33 = 7 + 9 + 11
43 = 13 + 15 + 17 + 19
. . . . . . . . . . . . . . . . . . . . . .

Based on this property, create a program that allows you to print a table of cubes of natural numbers.

Here two cycles are already needed. One is external , according to the number of odd numbers, which is equal to the number being cubed, for example, for 43 this loop should be executed 4 times. In the same cycle, after calculating the sum, it will be necessary to display its value on the screen along with the number that is cubed.
The second is internal , which will sum the odd numbers and " develop"required odd numbers for summation.


Block diagram

Rice. 36

Program

Program Problem3; (Cubes of natural numbers from 1 to n)
uses WinCrt;
var
i, j, n, s, k: longint;
begin
writeln("Enter the natural number to be reached");
write("print cubes of numbers"); readln(n);
writeln("The cubes of numbers are as follows:");
k:= 1;
for i:= 1 to n do
begin
s:= 0;
for j:= 1 to i do
begin
s:= s + k;
k:= k + 2
end;
writeln("The cube of the number ", i, " is equal to ", s)
end
end.

Let's look at how this program works

Variables i and j are needed as variables of the first - outer and second - inner loops. The variable k is for odd numbers, and s is for the sum of numbers. The type of these variables is set to integer, but longint, since there can be quite large integers larger than 32767.
The program begins with a request for the user, using the writeln and write operators, to enter a natural number, before which it is necessary to produce a table of cubes of numbers. This value is then entered into the computer's memory using the readln statement and assigned to the variable n.
The message " The cubes of numbers are as follows". It is given before the start of the loops for obvious reasons. It cannot be given in loops - it will be repeated several times. At the end of the loops too, then it will be written below, after the numbers themselves are output. The variable k is assigned the first odd value 1.
The outer loop begins based on the number of numbers, from 1 to n. There are several statements in the loop, so " open" operator brackets: - begin...
Before the start of the inner loop, the variable s - the sum - is reset to zero. Moreover, such a reset will occur every time the external loop, before executing the inner loop.
The inner loop runs from 1 to i. Why? The loop calculates the sum and increases odd k by 2, i.e. " is being produced" next odd number.

Notice! The variable k is not assigned before the start of each inner loop 1. Why?
The next writeln statement inside the outer loop prints information to the screen. Why is it placed in the outer loop?

Example 4. From mathematics it is known that every natural power of the number n is the sum of n consecutive odd natural numbers. Write a program that, for any power of a natural number n, would find a sequence of odd numbers whose sum is equal to this power.

For example, for 53 it would produce the sequence of numbers: 21, 23, 25, 27, 29.

Programming plan

1. Let’s determine the purpose of drawing up the program: it is necessary show , which is really any natural power of a natural number Can represent it as a sum of consecutive odd numbers.
And if this is so, then we absolutely need to know the value of the power of n with exponent k.
This can be done with a simple loop:

s:= 1;
for i:= 1 to k do s:= s*n;

The value of the degree will be accumulated in the variable s; for this, its initial value is set to 1.
In a loop, the value of the variable s is sequentially multiplied k times by the power of n. After executing the loop, the variable s will receive the value of the power of n with exponent k.
2. The whole urgency of the question lies in the fact that the first odd number is unknown, from which the summation of successive odd numbers must begin.
For this you need try add odd numbers first from 1 onwards (their number is known - n);
1 + 3 + 5 + 7 + 9 ...,
and then check the result obtained by comparing it with the value of the degree s. If the equality is true, then end the loop and display the resulting odd numbers on the screen; if the equality is not true, then you need to start the summation from the next odd number - 3: 3 + 5 + 7 + 9 ... etc.
This process is easier to organize using a loop repeat. The variable j, which will specify the initial odd numbers, must be set to the initial value 1 before the start of the loop.
General view of such a cycle:

j:= 1;
repeat
. . . . . .
j:=j+2
until...= s;

3. It remains to think about how to calculate the sums of consecutive odd numbers. We have already encountered this question and we know that for this we need to create a cycle from 1 to n, in which this amount should be accumulated in one of the variables, say m, and the second variable should " develop" next odd number.
This cycle can be written like this:

p:= j; m:= 0;
for i:= 1 to n do
begin
m:= m + p;
p:= p+2
end;

Pay attention! Variable p, every cycle repeat, (external to the given one), will receive a new initial value of the odd number, and the variable m - for the sum must be reset before each new summation for another sequence of odd numbers.
4. Finally, when the sequence of odd numbers is found, it must be displayed on the screen. To do this, we need to arrange another loop from 1 to n, in which we will output the values ​​of these odd numbers. For the first odd number in the sequence, we need to take the value j, but since it has already increased by 2, we should subtract 2 from j. This loop will be:

j:= j - 2;
for i:= 1 to n do
begin
write(j, " ");
j:=j+2
end

Block diagram

Rice . 37
Program

Program Problem4;
uses WinCrt;
var
n, i, k, j, m, s, p: longint;
begin
write("Enter a natural number - the base of the power "); readln(n);
write("Enter a natural number - exponent "); readln(k);
s:= 1; j:= 1;
for i:= 1 to k do s:= s*n;
repeat
p:= j;
m:= 0;
for i:= 1 to n do
begin
m:= m + p;
p:= p+2
end;
j:=j+2
until m=s;
write("Power with base ", n);
writeln(" and exponent ", k, " i.e. ", s);
writeln("equal to the sum of the following odd numbers");
j:= j - 2;
for i:=1 to n do
begin
write(j, " ");
j:=j+2
end
end.

To better understand its operation, take power 25 and check how the program statements will be executed sequentially.

1 . Run this program on computers.

2 . Create a flowchart and a program that determines whether a work can
a) three; b) four consecutive natural numbers equal some power of some natural number (square, cube, etc.)?

4. Different tasks

Example 5. Print all four-digit numbers whose decimal notation does not have two identical digits.

Comment . Before you start drawing up a flowchart for this task, you should know how loops within loops are depicted for loops with parameters. The general construction of two nested loops with parameters will be as follows:


Rice. 38
The idea immediately arises of creating a program according to the following scheme:
organize cycle by number of thousands, t from 1 to 9, and then internal cycles: by number of hundreds, s from 0 to 9; by number of tens, d from 0 to 9; by number of units, e from 0 to 9; condition check: If the numbers are different Then display a four-digit number made up of them on the screen.
Block diagram

Rice. 39
Program

Program Problem5; (1st method)
uses WinCrt;
var
t, s, d, e: integer;
begin
for t:= 1 to 9 do
for s:= 0 to 9 do
for d:= 0 to 9 do
for e:= 0 to 9 do
if(t<>s) and(t<>d) and(t<>e) and(s<>d) and
(s<>e) and(d<>e)
then write(t*1000 + s*100 + d*10 + e, " ")
end.

It is clear that this program was implemented irrationally. In it, all cycles are executed completely.
The program can be improved in this way. When the hundreds cycle is executed, then the next tens cycle must be started, If the hundreds digit s is not equal to the thousands digit t, otherwise, otherwise , the cycle of hundreds must be continued, i.e., take the next digit of hundreds.
For the tens digit, also set the condition that the next units loop will be executed, If the tens digit d is not equal to the hundreds and thousands digits, otherwise, otherwise , you need to move on to the next tens digit.
And then, " inside" cycle of units, it is enough to write the condition, If unit digits e are not equal to the tens digit d, hundreds s and thousands t, then the four-digit number is the searched one and it is displayed on the screen.


Block diagram

Rice . 40

Program

Program Problem5a; (2nd method)
uses WinCrt;
var
t, s, d, e: integer;
begin
writeln("All four-digit numbers from different digits");
for t:= 1 to 9 do
for s:= 0 to 9 do if s<>t then
for d:= 0 to 9 do if(d<>s) and(d<>t) then
for e:= 0 to 9 do
if(e<>d) and(e<>s) and(e<>t)
then write((((t*10 + s)*10 + d)*10) + e, " ")
end.

Task 4

1. Add and change this program so that it displays not only the various four-digit numbers, but also their number.

2. When multiplying a four-digit number consisting of different digits by 9, the product produced a number that differed from the multiplicand only in that there was a zero between the digits of thousands and hundreds. Find the multiplicand. Create a flowchart and program.

Example 6. Triples of natural numbers a, b, c, satisfying the equality: - are called Pythagorean numbers.
For example, 3, 4 and 5 are Pythagorean numbers because

Write a program to find and print all Pythagorean numbers not exceeding 20.

The math behind this question is simple. For numbers a, b and c, the possible values ​​are natural numbers from 1 to 20.
The initial value of a is one, a = 1. We will look through all possible values ​​of b from 1 to 20, as well as values ​​of c from 1 to 20 and check the equality a a + b b = c c. Once the equality is satisfied, then display the values ​​of a, b and c.
Next, you need to take the value a = 2 and check the values ​​of b from 2 to 20. Why not from 1, but from 2? Yes, because the set of two numbers from 1 and 2 has already been considered with the values ​​a = 1 and b = 2, so as not to repeat the values ​​of a and b, i.e. to avoid the appearance of two identical pairs of numbers, the values ​​of b should begin to be viewed or until the value a or from a until 20.
In this regard, there are several possible ways to organize loops for the variables a and b.
1st method:

for a:= 1 to 20 do
for b:=a to 20 do

2nd method:

for a:= 20 downto 1 do
for b:= 1 to a do

3rd method:

for a:= 1 to 20 do
for b:= 1 to a do

It is easy to see that with each of these methods pairs of numbers will not be repeated. Check it out for yourself.
For values ​​of c, we are required to check all natural numbers from 1 to 20 for each pair of numbers a and b. So the loop for c should be like this: for c:= 1 to 20 do

Block diagram

Rice . 41

Program

Program Problem6;
uses WinCrt;
var
a, b, c: integer;
begin
writeln("Triples of Pythagorean numbers from the interval ");
for a:= 1 to 20 do
for b:= 1 to a do
for c:= 1 to 20 do
if a*a + b*b = c*c then writeln(a, " ", b, " ", c)
end.

1. Create a block diagram and program that finds all solutions to the equation where n is a given number, from the interval .

2. Find all natural x from the interval for which the expression is the square of a natural number.

Example 7. In how many ways can a given natural number n be represented as the sum of two cubes of natural numbers:

Rearranging the terms does not give a new method. The operation of raising to the power of 1/3 cannot be used.

The following simple idea for creating a program immediately arises.

Organize two loops, one is an outer loop with variable i from 1 to n, and the second is an inner loop in j, also from 1 to n.

The essence of the program will be as follows:

the first value of i is 1, it is multiplied three times by itself (this replaces raising to the 3rd power);
then " are moving" all values ​​of j from 1 to n, each of which is also multiplied three times by itself and added to the value of i i i, i.e. i cubed;
further, this sum is checked to see if it is equal to the value n, if the equality is true, then the counter, which is obviously defined in the program, is increased by 1, and the values ​​of i and j can be displayed on the screen;
the loop through i continues, i takes on the second value - 2, and the inner loop through j from 1 to n starts executing again, and so on.
If we draw up a program according to this plan, it will have two significant drawbacks:
1) a lot of useless work is done - both loops are organized from 1 to n and there are many unnecessary ones among them (it is enough to take values ​​from 1 to the cube root of n);
2) the program will produce values ​​that are obtained by rearranging the terms, for example: 2 2 2 + 3 3 3 = 35 and 3 3 3 + 2 2 2 = 35, which is unacceptable according to the conditions of the problem. How to eliminate these shortcomings?
We can eliminate the first drawback if we first find out how many values ​​for each of the numbers must be considered in order for the inequality to hold
To do this, you can organize a loop with a precondition, a loop " Bye ", in which to include a counter - k, which would count how many times such a loop will be executed.

This can be done like this:

k:= 0; i:= 1;
while i*i*i + 1<= n do
begin
k:= k + 1;
i:= i + 1
end;


Now you can significantly reduce the number of cycles for " subjects" numbers and organize them from 1 to k, because for values ​​of i greater than k, even for the smallest value of j (j:= 2) the inequality i i i + 1<=n не выполняется.
To eliminate the second drawback, i.e., in order not to produce options with rearrangement of terms, you can do this:

arrange the outer loop for i of the first number from k to 1, and make the inner loop for the second number for j from 1 to i. You will get this part of the program:

p:= 0;
for i:=k downto 1 do
for j:= 1 to i do
if i*i*i + j*j*j = n
then
begin
p:= p + 1;
end;

Carefully look at this part of the program and think about why in this case we avoid repeating options and exclude cases of rearrangement of terms?

Left Beautiful finish the program. After all, very often there will be cases when a number cannot be represented at all as the sum of the cubes of two numbers. This circumstance must also be taken into account.

To do this, after executing all the loops, we will introduce a conditional operator in which, depending on the values ​​of the counter p, the corresponding messages will be issued.

If p = 0, Then display a message that the number cannot be represented as the sum of the cubes of two numbers, and otherwise, display a message about the number of ways.
This part of the program can be executed like this:

if p = 0
then
begin

end
else


Block diagram


Rice . 42

Program

Program Problem7;
uses WinCrt;
var
i, j, n, k, p: longint;
begin
write("Enter a natural number"); readln(n);
k:= 0; i:= 1;
while i*i*i + 1<= n do
begin
k:= k + 1; i:= i + 1
end;
p:= 0;
for i:=k downto 1 do
for j:= 1 to i do
if i*i*i + j*j*j=n
then
begin
p:= p + 1;
writeln(i, "*", i, "*", i, "+", j, "*", j, "*", j, "=", n)
end;
if p = 0
then
begin
write("The number ", n, " cannot be represented as ");
writeln("sum of cubes of two numbers")
end
else writeln("The number of ways is ", p)
end.

Another solution to this problem

Program Problem7b;
uses WinCrt;
label 1, 2;
var
i, j, m, k, n: longint;
begin
write("Enter a natural number"); readln(n);
m:= 0; i:= 1; j:= 1;
while j*j*j + 1< n do j:= j + 1;
repeat
k:= i*i*i + j*j*j;
if k = n then m:= m + 1;
if k<= n then i:= i + 1;
if k >= n then j:= j - 1;
until i > j;
if m = 0 then goto 1;
write("The number ",n," can be represented as a sum");
writeln(" cubes of two numbers ",m," ways"); goto 2;
1: write("This number is not representable");
writeln("sum of cubes of two numbers");
2: end.

Natural n is given. Can n be represented as the sum of three squares of natural numbers? If possible, then indicate all triples x, y, z such natural numbers that Rearranging the terms does not give a new method. Create a flowchart and program.

5. Type Conversion

Example 8. A two-digit decimal number added to a number written in the same digits, but in reverse order, gives a complete square. Find all such numbers.

Let the required two-digit number = a 10 + b, then the number written in the same numbers, but in reverse order will be = b 10 + a, for example, 12 and 21, 13 and 31, etc.
The sum of these numbers should give a complete square, i.e. the exact square of integers. How can I check this?
The check could be done like this: take the square root of the resulting amount; then round the result to a whole number, and then multiply the resulting result by itself, if the sum of these numbers is again obtained, then it means it is an exact or perfect square.
For example, 12 + 21=33, take the square root of 33, it is equal to 5.74...; round, it will be 6; multiply 6 by itself and get 36.
We didn't get the original result, which means the sum of 33 is not an exact square.
One more example so that you understand the idea of ​​the solution. Let the two-digit number be 29, then the number written with the same digits, but in reverse order is 92, in total they give 121. We take the square root of 121 and get 11. Multiplying 11 by itself, we again get 121. We conclude that we have obtained an exact square, which means the two-digit number 29 is the desired one.
To write a program using this principle, you will have to take the square root of the sum, which can be done using the standard sqrt(x) function. The result of the sqrt(x) function is a real number, it must be rounded or discarded, and we do not know how to do this.
But, even more significant, is that if the square root in the set of integers is taken in its entirety, as for 121 (it is equal to 11), then in the set of real numbers we will not strictly get the number 11, but the result will be very close to 11 and after multiplying by itself will still not yield 121, i.e. the need arises convert real value to integer.
So we have two tasks: 1) figure out how to round numbers and; 2) establish how to convert a real type to an integer.

For this purpose, Pascal has standard functions round(x) and trunc(x)

Standard Features round And trunc are intended to replace values ​​of a real type with values ​​of an integer type.
Function round(x) rounds the real number x to an integer - its value is the nearest integer:
round(4.2) = 4, round(4.7) = 5, round(4.5)=5,
round(-4.2) = -4, round(-4.7) = -5, round(-4.5) = -5.
Function trunc(x) discards (without rounding) the fractional part of the real number x:
trunc(1.2) = 1, trunc(5.8) = 5, trunc(-1.2) = -1,
trunc(-5.8) = -5, trunc(-6.7) = -6, trunc(8,9) = 8

The rounding functions are related like this:
trunc(x + 0.5) = round(x), If x 0,
trunc(x - 0.5) = round(x), If x< 0.
So, you can use one of these functions in the program. Which? Think for yourself and try using the function in the program first trunc, and then replace it with round and compare the results.

  • Show that a four-digit number in which the thousands and tens digits are the same and the hundreds and ones digits are also the same cannot be an exact square.
  • The product of six consecutive natural numbers can be equal to the product of three consecutive natural numbers. For example, 1 2 3 4 5 6 = 8 9 10 = 720. Are there other numbers like this?
  • Prove that the product of four consecutive integers added to one gives a perfect square.
  • Find 11 consecutive natural numbers whose sum of squares is the square of the integer.
  • Are there any integers that are reduced by a factor of 57 when their first (left) digit is crossed out?
  • Find a four-digit number, knowing that it is the square of a natural number and that its digits fall into two pairs consisting of identical digits.
  • Find all seven-digit numbers that are divisible by 15 and written only as 0 and 1.
  • A six-digit number begins with the number 1. If this number is moved to the end of the number, the new number will be three times larger than the original. Find the number.
  • How many exact squares can be made from the numbers 3, 4, 5, 6?
  • Given 20 different natural numbers not greater than 50. Find two of them whose difference is 4, 5 or 9.
  • How many times will a two-digit number increase if the same two-digit number is added to its right?
  • Determine the greatest value of the ratio of a three-digit number to a number equal to the sum of the digits of this number.
  • Find a three-digit number that is a multiple of 45 if the difference between this number and the number written in the same digits, but in reverse order, is 297.
  • Find a four-digit number that is a multiple of 11, provided that b + c = a is a perfect square.
  • Find a three-digit number equal to the sum of the tens digit, the square of the hundreds digit and the cube of the units digit.
  • Find two numbers whose product is a three-digit number, which is the cube of a certain number, and the quotient is the square of this number.
  • The difference between a number and the product of its digits is equal to the sum of the digits of that number. Find this number.
  • Find all values ​​of the number m for which the sum is 1! + 2! + , + m! is a perfect square.
  • Find a positive four-digit number that is a multiple of 7 and is the sum of the cube and the square of a certain number.
  • A certain number when divided by 7 leaves a remainder of 3; its square when divided by 72 gives a remainder of 44; its cube when divided by 73 gives a remainder of 111. Find this number.
    1. For what natural value of a will the number a2 + a + 1589 be a perfect square?
    2. Find a perfect number of the form 16p.
    3. Find two numbers if the sum of their squares is 468 and the sum of their common greatest divisor and least multiple is 42.

    We have already considered a cycle with a parameter in the “Algorithm” section in the topic “Types of algorithms”.
    A loop with a parameter is used,when it is known in advance how many times the loop should be executed.

    Cycle recording format:

    Here for, to, do- reserved words (for, to, perform);

    <пар. цикла> - loop parameter – variable integer type (type integer);
    <нач. знач.> - initial value - number or variableinteger type (type integer);
    <кон. знач.> - final value - number or
    variableinteger type (type integer);
    <оператор> - arbitrary Pascal operator.

    Example: For i:=1 to n do<оператор>
    here i is the loop parameter
    1 - initial value
    n - final value
    If several statements are used in the body of the loop, then operator brackets are used: begin ... end.
    When executing a for statement, the expression is first evaluated<нач.знач.>and its value is assigned to a loop variable<пар.цикла> := <нач. знач.>. Next they compare<пар.цикла>And <кон.знач.>. Until they become equal, the operator(s) will be executed. Loop Variable Value<нач.знач>automatically increases by one during the loop.It should be immediately noted that it is impossible to set a cycle step other than 1 in this operator.
    Example:
    The following loop operator entries are possible:

    1) for i:= 1 to n do s1;

    2) for i:= 3 to 10 do s1;

    3) for i:= a to b do s1;

    4) for i:= a to b do
    begin

    s1;
    s2;
    ...
    sn

    end;

    Here s1, s2, s3, ... sn are loop operators.

    Example:
    Write a program to display numbers from 1 to 10.

    Example:
    Write a program for calculating the factorial of the number n, i.e. n!. (0!=1)

    Program explanation:
    Variable n - for a number entered by the user, the factorial of which must be found; f is a variable in which the value of the factorial of the number n will be “accumulated”; i is a loop variable.
    The initial value of the variable f:= 1 is set.
    Then the cycle begins. The variable i is assigned the initial value 1; it is compared with the final one - n (1<= n), если условие истинно, тогда выполняется оператор (в этой программе он один): f:= f*i, 1*1=1; значение переменной цикла увеличивается на 1, т. е. станет равным: i:= i + 1, 1 + 1 = 2 и цикл повторяется.
    When the value of i becomes equal to n, then the loop will be executed for the last time because the next value of i will be n + 1, which is greater than the final value of n, condition i<= n - ложно, цикл не выполняется.

    There is another form of the For loop statement:
    Cycle recording format:

    Replacing the reserved word to with downto means that the loop parameter step is (-1).
    The parameter value changes from a larger value to a smaller one, i.e.<нач. знач.> <кон. знач.>.

    Example:
    The following loop operator entries are possible:

    1) for i:= n downto 1 do s1;

    2) for i:= 10 downto 3 do s1;

    3) for i:= b downto a do s1; (provided that b>a)

    4) for i:= b downto a do
    begin

    S1;
    s2;
    ...
    sn

    end; (provided that b>a)

    Here s1, s2, s3, ... sn are loop operators.

    Example: Calculation program factorial numbers can be composed using this loop operator.


    Tasks

    1. Given 10 numbers, print those that are perfect squares.
    2. Given 10 numbers, find their product.Create a flowchart and program.
    3. Given 10 numbers, find the sum of the even ones.Create a flowchart and program.
    4. Given 10 numbers, find the number of negative ones.Create a flowchart and program.
    5. Given n real numbers. Find the maximum and minimum.Create a flowchart and program.
    6. Given n real numbers. Find the arithmetic mean of all elements.Create a flowchart and program.
    7. Given n real numbers. Find the arithmetic mean of negative and positive elements.Create a flowchart and program.
    8. Given n natural numbers. Find the sum and product of elements that are multiples of 3 and 5.Create a flowchart and program.
    9. Given n natural numbers. Withdraw those numbers whose values ​​are powers of two (1, 2, 4, 8, 16, ...).Create a flowchart and program.
    10. Given n natural numbers. Withdraw those numbers whose values ​​are in the interval.Create a flowchart and program.
    11. Given n natural numbers. Display those numbers whose values ​​are the squares of some number.Create a flowchart and program.
    12. Given a natural number n. Find n 2.Create a flowchart and program.
    13. Given natural numbers a, n. Find a n.Create a flowchart and program.
    14. Given a natural number n. Determine its bit depth, increase the most significant digit of the number by 2
    15. Given a natural number n. Swap the first and last digits of a number
    16. Given a natural number n. Replace digits of a number that are multiples of 2 with 0.
    17. Given a natural number n. Replace digits of numbers that are multiples of 3 by 1.
    18. Given a natural number n. Calculate the product (2n-1)*(3n-1)*(4n-1)*...*(10n-1).Create a flowchart and program.
    19. Calculate the sum 2+4+6+...+100.Create a flowchart and program.
    20. Given a natural number n, a real number x. Calculate the product x+x/2+x/3+...+x/n.Create a flowchart and program.
    21. Given a natural number n. Calculate P=(1-1/2)(1-1/3)...(1-1/n), where n>2.Create a flowchart and program.
    22. Given a natural number n. Calculate P=(1+x)/n+(2+x)/(n-1)+...+(n+x)/1.Create a flowchart and program.
    23. Given n natural numbers. Calculate the sum of a series1+x/1!+x 2 /2!+x 3 /3!+ ...+x n/n!. Create a flowchart and program.

    The loop operator with a parameter is used precisely in cases where it is necessary to organize a loop with a specified number of repetitions

    for <параметр_цикла>:=<начальное_знач> to <конечное_знач> do <оператор>;

    for <параметр_цикла>:=<конечное_знач> downto <начальное_зна.> do <оператор>;

    The statement that represents the body of the loop can be simple or compound.

    The loop parameter, as well as its range of change, can only be of an integer or enumerated type.

    The parameter is described together with other variables.

    The for loop step is always constant and equal to "1" or "-1".

    Print the first ten positive integers

    var i: integer; //enter counter

    fori:=1to10do//while the counter value is from 1 to 10 do the following

    writeln(i); //output counter value

    vari,sum:integer;

    sum:=0; //resetting the value of the variable

    fori:=10to99do//searching for two-digit positive numbers

    if i mod 3=0 then //multiplicity 3

    sum:=sum+i; //sum of the previous value of the variable and the number corresponding to the condition

    Display the product of the first ten even positive numbers

    vari,pr:integer;

    pr:=1; //when finding the product, the initial value of the variable is not 0, but 1

    for i:=1 to 10 do

    if i mod 2=0 then //determine parity

    Given two integers A and B (A< B). Вывести в порядке возрастания все целые числа, расположенные между A и B (в том числе A и B), a также количество N этих чисел .

    var i,pr: integer;

    k:=0; //reset the value of the variable indicating the quantity

    fori:=AtoBdo//search numbers from a given range

    writeln(i); //output in numbers in ascending order

    k:=k+1; //count the number of numbers

    writeln(k); //the output of the quantity occurs outside the loop because displayed once

    Enter N different numbers. Find the arithmetic mean of all numbers.

    Var n,i,a:integer;

    For i:=1 to N do

    Writeln("arithmetic mean= ",s/n:4:2);

    Loop operator with precondition while ... Do (for now...)

    The while ... do operator is designed to implement loops with a precondition.

    The execution condition of the while loop body is checked before the start of each step. Therefore, if the condition is not immediately satisfied, then the body of the loop is ignored, and control is transferred to the operator immediately following the body of the loop.

    Contacting the operatorwhile ... do translates as “for now... do” and looks like this:

    while <условие> do <оператор>

    The while loop implies the following algorithm: while the condition is true, the statements of the loop body are executed.

    The condition itself can be a Boolean constant, a variable, or a Boolean expression.

    When writing loops with a precondition, keep the following in mind.

      For a cycle to have a chance of ever ending, the contents of its body must necessarily influence the condition of the cycle.

      the condition must consist of correct expressions and values ​​defined before the first execution of the loop body.

    If the loop condition is false, the loop will not be executed even once!

    Loop statements with parameter (for)

    Loop statements with a parameter (which begin with the word for) causes a statement (which may be a compound statement) to be executed repeatedly while an increasing sequence of values ​​is assigned to the control variable.

    For loop parameter:= start value to end value do statement.

    The variable identifier must be used as the control variable. The control variable must be an enumerated type. The start and end values ​​must be of a type that is assignment compatible with the enumeration type. When does the statement start executing? for, the start and end values ​​are determined once, and these values ​​are maintained throughout the execution of the statement for. A statement that is contained in the statement body for, is executed once for each value in the range between the start and end values. The control variable is always initialized to an initial value. When the operator works for and the keyword is used to, the value of the control variable increases by one with each repetition. If the initial value exceeds the final value, then the body of the statement for operator will not be executed. When a keyword is used in a loop statement downto, the value of the control variable decreases by one with each repetition. If the initial value in such a statement is less than the final value, then the statement contained in the body of the loop operator will not be executed.

    If the statement contained in the body of the statement for, changes the value of the control variable, this is an error. After executing the statement for the value of the control variable becomes undefined unless the statement is executed for was not interrupted by a jump operator.

    To the loop parameter in the statement for the following restrictions apply:

    1) the loop parameter, as well as its initial and final values, cannot be changed by any operator in the body of the loop;

    2) entering the cycle ONLY through its beginning.

    Array is an ordered collection of variables of the same type, called array elements. All elements have the same name, which is the same as the array name. Each element is provided with an index (ordinal number), which determines its relative position in a series of other elements, and is called an indexed variable. The index of an element is written after its name in square brackets, for example, a, max, etc. The characteristics of each array are its name, dimension and length. The array name is chosen according to the same rules as the name of a simple (non-indexed) variable. The concept of array dimension is similar to the concept of matrix dimension in mathematics. So a one-dimensional array corresponds to a vector - a row, a two-dimensional one - to a matrix of the same dimension, etc.



    Array length is the number of its constituent elements. Arrays are one of the varieties of the composite type, namely the regular type.

    The definition of a regular type is

    array of t1

    Where array - array (keyword);

    of - from (keyword);

    t1 - type of array elements (base type);

    t2 - type of array element indexes.

    Array elements can be variables of any type allowed in the language. The index type specifies the number of elements in the array, i.e. its length; this number is determined by the number of possible values ​​of the type specified in the array description. To index array elements, a restricted type is most often used, which is formed from some standard type (for example, an integer) by imposing restrictions on the permissible range of its values. These restrictions are specified by the minimum and maximum index values, separated by two consecutive periods and enclosed in square brackets, for example, [-5..35], etc.

    In the program, each array must be described. Its description can be made either in the variable description section - var , or in two sections: type descriptions - type and variable descriptions. But in any case, the array description must contain a definition of a regular type.

    The array description in the variables section looks like this:

    var

    array name: array of t1;

    Loops occupy a special place in Turbo Pascal. They begin to study them immediately after mastering the skills of input and output of information on the screen. After all, most problems come down to the fact that loops with a parameter and other constructs help facilitate the writing and functioning of a certain program block.

    Types of cycles

    There are three types in total:

    • with the parameter
    • with a precondition,
    • with a postcondition.

    Loops with a parameter, otherwise they are called For ... to ... do or For ... downto .... do, repeat a certain sequence of actions many times. In principle, other varieties are used for the same purpose, only in the for loop the number of steps is known in advance.

    In the other two constructs (While and Repeat), the number of iterations is initially unknown. Therefore, when studying the task, it is already necessary to understand which cycle will be used.

    Basic definitions on the topic

    Loops with parameters are repeated iterations. The counter is the main indicator with the help of which a given design is carried out. The boundaries of the interval show within what limits certain iterations will be performed. By the way, it is not at all necessary that the initial value be equal to 1. The user independently sets both boundaries of the interval. The body of the loop is a set of commands for which the number of repetitions has already been determined.

    The concept of “loops with parameters” means that in this design a condition is checked, after which a set of iterations is performed. The counter increases (or decreases) and everything repeats. The body of the loop will be executed as long as the condition is true.

    For ... to ... do: operating algorithm, syntax

    As already mentioned, loops with a parameter are used in tasks that specify the “interval” in which to work. So, this could be an array of numbers, days of the week, lines of a poem, etc.

    There are 2 types of design: for increasing the counter and for decreasing it. The first construction will be written as follows:

    for original variable := border 1 to border 2 do

    loop body;

    Here: ref. variable declared by the user at the beginning of a program or block; border 1 and border 2- initial and final value of the interval; V body cycle a number of actions are prescribed that must be performed by the program. It must be remembered that if the body of the loop contains only 1 command, then the operator brackets begin...end can be omitted. In this version of the design, the counter, namely<исх.переменная>, will increase in increments of 1.

    for original variable:= border 1 downto border 2 do

    loop body;

    Here is the ref. the variable will decrease in increments of 1.

    The loop operation diagram with the For... to... do parameter will look like this:

    • The value of the upper boundary of the interval is set, i.e. border 2.
    • Source variable the parameter value is assigned border 1.
    • The condition is being checked: original variable ≤ limit 2.
    • Upon receiving the result True (True) the body of the loop is executed.
    • The counter is incremented by steps equal to 1.
    • Steps 3-5 are executed exactly until the condition is true: original variable > limit 2. As soon as this happens, the loop exits and control is transferred to the command following this construction.

    In For... downto... do, the operating algorithm is similar to the above, with the exception of some points:

    • In the 3rd paragraph the condition is checked: original variable ≥ limit 2.
    • In the 5th line of the algorithm, the counter is decreased by 1.
    • In the 6th paragraph, commands 3-5 will be executed until the condition is satisfied: original variable< граница 2.

    Everything else is similar in both operating algorithms.

    Block diagram of a cycle with a parameter

    Cycles with a parameter have the following block diagram (although it has already been presented above). A simplified organization of the design is also shown here.

    Basic requirements for a cycle with a parameter

    Loops with parameters require certain kinds of conditions.

    • The counter and span boundaries (i.e., source variable, boundary 1, and boundary 2) must be of the same data type. If there is only compatibility between the start and end values ​​of the segment and the source variable, then the program may behave incorrectly because the boundaries will be converted to the data type of the source parameter.
    • The data type to which the parameter values ​​must belong must be integer. It is highly recommended not to use the real type.
    • It is not advisable to forcibly change the value of the original variable parameter in the body of the loop. Otherwise, the user will have difficulty tracking down possible errors that may appear.
    • Unlike other types of loops, in For ... to ... do or For ... downto ... do the step cannot change by a parameter other than 1.

    Turbo Pascal: how to break out of a loop

    There are often problems in which looping occurs, i.e. the condition being checked is always true. The Break procedure helps to break out of loops with a precondition, postcondition, and parameter. That is, their work is terminated ahead of schedule.

    Loops with pascal parameters (the programming of which assumes the “eternal” truth of the condition) can be stopped using Continue. Here the work is organized as follows: the current iteration ends its execution ahead of schedule, control is transferred to the next command, but without exiting the loop.

    The Exit procedure is necessary in order to complete the work of a particular block in program code. It is called inside a procedure (function) and at the same moment, the execution of this “piece” immediately stops. If Exit is in the main block of the program, then it terminates its work.

    The Halt procedure reduces the operating principle to the following: the program ends completely.

    Examples of tasks with solutions

    It will be useful for the user, after studying the topic “Loops with parameters in Pascal,” to first study the examples and then practice writing code on their own. Simple tasks help the future programmer learn theory in practice, and then successfully apply it. On the topic “Loops with a parameter,” examples of problems with solutions can be found easy and complex. Here are 3 problems that explain the algorithms and provide explanations and comments for each solution.

    Problem 1

    Dan two-dimensional array natural numbers in the range chosen at random. Find the number of all two-digit numbers whose sum of digits is a multiple of 2.

    Algorithm of actions:

    1. Create a two-dimensional array.
    2. Check each number to see if it meets the following conditions:

    a) if 9< Х < 100, то разделить его нацело на 10 посредством div;

    b) select the second digit of a number by dividing via mod;

    c) add the highlighted numbers;

    d) divide the given amount by 2 using mod;

    e) if the result is 0, then the counter is incremented by 1.

    Problem 2

    Given a one-dimensional array of integer elements. Find the number of positive numbers.

    Algorithm of actions:

    1. Create an array of integer elements created by randomize.
    2. In a loop with a parameter, insert an IF that will check the given element for compliance with the condition: X>0.
    3. If the condition is met, the counter is incremented by 1.
    4. After the cycle, the resulting counter value should be displayed.

    Data given in parentheses () are comments. In line 11, you can display the array on the screen in two ways: leave a space between the numbers or allocate a certain number of cells for each element (in this case there are 5).

    In line 12, the counter variable can also be increased in two ways: either by adding 1 to the previous value, or by using the standard Inc function.

    Problem 3

    Given a square matrix. Find the number of positive elements located on the main diagonal.

    Explanations:

    In an array of numbers, the main diagonal extends from the upper left corner to the lower right. Its peculiarity is the fact that the row and column indices coincide. Therefore, it is enough to organize 1 loop to move through the lines without enumerating the remaining elements.

    Algorithm of actions:

    1. Create a square matrix.
    2. Assign the value “0” to the variable responsible for counting positive elements.
    3. Create a cycle to create a square matrix.
    4. Organize a loop to check the condition: if the number on the main diagonal is >0, then the counter is incremented by 1.
    5. After the loop ends, display the value of the variable storing the number of positive elements.

    Confrontation between two programming languages: C and Turbo Pascal

    As a rule, a self-respecting programmer knows several languages. For example, it could be C++, Turbo Pascal, Delphi, Java, etc. The opposition between the two of them was clearly expressed back in the 80s. (C and turbo pascal). At the end of the twentieth century, the same struggle was observed between C++ and Java.

    In the virtual space, among three dozen programming languages, one can distinguish three of the brightest pairs, the confrontation of which amazed the greatest minds of cyberspace: ALGOL-60 and Fortran, Pascal and C, Java and C++. Of course, these feelings are subjective, but at one time or another one of the pair was the leader. This was explained by the requirements of industry and the need for one or another software product. In the 70s Fortran “ruled the world”, in the 80s - Turbo Pascal, in the 90s - C++. Of course, none of them "died". Rather, they have transformed into advanced software products.

    When learning programming languages, you may notice that some topics have similar syntax. Thus, loops with a parameter in C are similar to similar constructs in Pascal, with the exception of some points.

    It is interesting that the developers of Turbo Pascal (Old World) used the results of the developments of American scientists, while in the New World they actively applied the results of research by European specialists. In Europe, developers advocate more for the purity and compactness of programming languages, while American minds are more inclined to use newfangled trends in coding.


    Close