§9 Loop instruction with the for parameter. A for loop based on a range. Loops with parameters Which loop is called a loop with a parameter

A loop with a parameter has the following format:

for (initialization; expression; modifications) statement;

Initialization used to declare and assign initial values ​​to quantities used in the loop. In this part, you can write several statements separated by a comma (the “sequential execution” operation), for example, like this:

for (int i = 0, j = 2; ...

for (k = 1, m = 0; ...

The scope of variables declared in the initialization part of the loop is loop 1. Initialization is performed once at the beginning of the loop execution.

Expression defines the condition for executing a loop: if its result, cast to type bool , is true, the loop is executed. A loop with a parameter is implemented as a loop with a precondition.

Modifications are executed after each iteration of the loop and are usually used to change the parameters of the loop. In the modification part, you can write several statements separated by commas. Simple or compound operator represents the body of the loop. Any part of the for statement can be omitted (but the semicolons must be left in place!).

Example (operator that calculates the sum of numbers from 1 to 100):

for (Int i = 1, s = 0; 1<=100; i++) s += i;

Example (the program prints a table of function values y=x 2 +1 in the entered range):

#Include

float Xn, Xk, Dx, X;

printf("Enter the range and increment of the argument: ");

scanf (“%f%f%f”, &Xn, &Xk, &Dx);

printf("| X | Y |\n");

for (X = Xn; X<=Xk; X+=Dx)

printf (" | %5.2f | %5.2f |\n”, X*X + 1);

Example (the program finds all divisors of a positive integer):

#Include Int main())(

Int num, half, div;

cout<< “\n Введите число: "; cin >>num;

for (half = num / 2, div = 2; div<= half; div++)

if (!(num %div))cout<< div <<"\n";

The last two examples perform the same actions as the examples for a loop with a precondition, but are written more compactly and clearly: all actions related to controlling the loop are localized in its header.

Any while loop can be converted to an equivalent for loop and vice versa using the following scheme:

for (b1: b2; bЗ) operator b1;

while (b2)( operator; bЗ;)

Frequently occurring errors when programming cycles - use of uninitialized variables in the loop body and incorrect entry of the loop exit condition.

q check whether all variables appearing on the right side of assignment operators in the body of the loop have previously been assigned initial values ​​(and also whether other operators can be executed);


q check whether at least one variable included in the loop exit condition changes in the loop;

q provide for an emergency exit from the loop upon reaching a certain number of iterations;

q and, of course, do not forget that if you need to execute more than one statement in the body of the loop, you need to enclose them in curly braces.

The loop operators are interchangeable, but some recommendations to choose the best in each specific case.

The do while statement is usually used when the loop must be executed at least once (for example, if data is entered in the loop).

The whiIe operator is more convenient to use in cases where the number of iterations is not known in advance, there are no obvious loop parameters, or it is more convenient to write modification of parameters not at the end of the loop body.

The for operator is preferable in most other cases (definitely for organizing loops with counters).

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.

In general terms, today we will learn about each of the cycles in Pascal in more detail and see how they are defined. We'll sort it out while loop with precondition, for loop with parameter And repeat - until loop with postcondition.

1. Loop with a parameter in Pascal - FOR

The FOR loop sets a certain condition under which the program will work before it is executed. Let’s say we need to loop the program 5 (or n) times, then this can be easily done using this loop. The FOR loop has a characteristic feature - a counter, which is usually denoted by the letter i or j.

Appearance of a loop with a parameter in Pascal:

for i:= 1 to n do // assign i first to one, then to two, three, ..., n

After the 1st pass, we assign 1 to the variable i, after the second we assign 2, and so on until we reach n. to - this is up to.. in ascending order, there is also downto - up to.. in descending order.

Block - cycle diagram with parameter:

2. 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. Since the validity of the logical expression is checked at the beginning, the body of the loop may not be executed even once.

Loop structure with precondition:

WHILE DO begin end;

A logical expression whose truth is checked at the beginning of the execution of the cyclic operator;

Any executable language statements.

Loop execution order:

While the condition is true, the body of the loop is executed. As soon as the condition becomes false, execution of the loop stops.

Block - diagram of a cycle with a precondition:


Note: rectangular blocks show any action that is performed in a loop or after it (loop step), while oval blocks show the beginning or end of the entire program or part of it. The main role in this block diagram is played by its central part.

Example:

Task: calculate the sum of the series 1+1.5+2+2.5+3+3.5+ .. + 30

program example-while;

Var sum:real; n:real; BEGIN sum:=0; n:=1; while n

3. Loop with postcondition - 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 loop operator assumes that there are several statements in the loop body, that is, several actions can be performed, so the Begin and End service words are not needed.

The sequence of operators included in the body of the loop is executed once, after which the condition written after the service word Until is checked. If the condition is not met, the loop ends. Otherwise, the body of the loop is repeated again, after which the condition is checked again.

Block diagram of a cycle with a postcondition:

Recording format, cycle structure:
REPEAT UNTIL;

Example:

Program test2; Var b:Real; Begin b:=100; Repeat b:=b/2; Until b

Conclusions:

1. A loop with a parameter uses a variable called a loop parameter or counter. Before the loop is executed, the parameter (counter) is set to its initial value. After completing a loop step, the parameter value is increased by one. The loop continues until the parameter reaches its final value, which is indicated after to (downto).

2. The precondition loop runs until the execution condition becomes false and continues if the condition is true.

3. The loop with a postcondition is executed until the condition becomes true, if the condition is false, the loop continues.

The for loop statement implements the algorithmic structure loop with parameter(or a loop with a counter). The for loop is used when in a program, before executing the loop instructions, the number of steps in this loop becomes known (or is predetermined). In a block diagram, the for statement is represented as follows:

Syntax:

For( initialization; condition; modification) (Loop body instructions; )

If there is one instruction in the body of the loop, then ( ) can be omitted. The loop parameter variable (counter) can be of any numeric type. This makes the C++ for loop as versatile as a while loop. The modification section most often uses a postfix or prefix increment (or decrement) operation, but any assignment expression that changes the value of a loop parameter can be used. The cycle works like this:

  • At the beginning, the counter variable is described and initialized
  • Next, check the condition: if the expression has a value true, iteration will occur
  • After executing the instructions of the loop body, the counter value is modified

Note: In C++ it is a rule to declare the counter variable in the loop head. But this is not necessary, especially if you plan to initialize several variables in the initialization section as implemented in program 9.2. However, using a counter variable declaration in a loop header results in a local variable declaration that is destroyed automatically when the loop ends. Therefore, unless absolutely necessary, you should not define a counter variable outside a for loop.
While the for loop is running, it is not recommended to change the operands in the loop header expressions - this will lead to all sorts of errors! But the values ​​of variables (or constants), including changeable values ​​(counter), can be used. Let's look at a classic example.

Program 9.1 Given a natural number N. Print all divisors of this number.

#include << "N = "; cin >> N; for (int i = 2; i< N / 2; i++) { if (N % i == 0) cout << i << " "; } return 0; } N = 16000 2 4 5 8 10 16 20 25 32 40 50 64 80 100 125 128 160 200 250 320 400 500 640 800 1000 1600 2000 3200 4000

Using the continue statement in a for loop

When using the continue statement in a for loop, you must take into account the peculiarities of how this loop works:

  • Statements following continue will be skipped
  • Then the counter is modified
  • Move to the next iteration (otherwise, checking the condition)

Let's show this with an example: int main() ( for (int i = 1; i< 20; i++) { if (i % 2 == 0) continue; cout << i << " "; } 1 3 5 7 9 11 13 15 17 19

Note. Please note: although the output of numbers by condition is skipped, the counter is incremented. This example is for illustrative purposes only; this is not the way to program a loop! This problem is better solved as follows:

Int main() ( for (int i = 1; i< 20; i += 2) cout << i << " ";

Several expressions in the initialization and modification section

As we noted earlier, the head of the for statement must have three sections. Expressions in these sections can be omitted, but ";" cannot be omitted. . In the end, one can only leave; . Heading in the form:

For (;;) ( ... )

is the header of an “infinite” loop. (The exit from the loop must be programmed within the body of the loop.)
C++ supports several expressions in the initialization and modification sections of the head of a for statement. In this case, the condition for continuing the cycle must be one!
For example. Problem statement: Calculate the factorial of a number not exceeding 20.
Program 9.2

#include using namespace std; int main() ( unsigned long long n; int i, k; cout<< "k = "; cin >>k; // 0<= k <= 20 for(n = 1, i = 1; i <= k; n *= i, ++i); cout << k << "! = " << n << endl; return 0; } k = 20 20! = 2432902008176640000

Note: Note that the output stream on line 12 is not part of the loop body! (At the end of the title - ;). Thus, this loop has an empty instruction in the body, and all expressions are evaluated in the header. Program 9.2 correctly calculates the factorial of a number from 0 to 20.

range-based for loop

To iterate through the elements of an array or container, you have to perform the same type of actions and use cumbersome code. To simplify working with containers in C++, there is a special form of the for loop - range-based for (loop for range based or range for).
Syntax:

For( announcement : sequence_name) loop_statement

Using range-based for using a C array as an example:
Program 9.3

#include using namespace std; int main() ( int x ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ); for (auto &s: x) ( cout<< s << " "; } return 0; }

In order for array elements to be changed, the variable s must be a reference variable (as in the example above). If the variable is not a reference, then the data will be copied. To automatically infer the type, this loop uses the auto specifier. range-based for has a limitation when working with dynamic arrays: it does not support changing the size of the array, since it contains a fixed pointer to the end of the array. When working with arrays that have a fixed size, range for is an excellent and safe alternative to regular for .

Nested for loops

Just like other loop statements, for supports a nested loop structure. Using nested for loops to organize the input and output of two-dimensional arrays is much more compact than using a while loop.
However, when solving problems of traversing such arrays, it is necessary to avoid using the conditional if statement. Often, the task can be implemented more rationally by manipulating the indices (loop variables i and j). That is, to make the change in one index dependent on the value of another. Let's look at two examples.
Program 9.4 Given a square matrix of size n, the elements of which are equal to 0. Fill the elements lying below and on the main diagonal with ones.

#include using namespace std; int main() ( int n; cout<< "n = "; cin >>n; int mas[n][n]; // Fill with zeros for(int i = 0; i< n; i++) for(int j = 0; j < n; j++) mas[i][j] = 0; // Реализация for(int i = 0; i < n; i++) for(int j = 0; j <= i; j++) mas[i][j] = 1; // Вывод for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cout.width(2); cout << mas[i][j]; } cout << "\n"; } return 0; } n = 10 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1

Program 9.5 Write a program to fill an array with numbers from Pascal's triangle and output this array. Pascal's triangle looks like:


In this triangle, there are ones at the top and on the sides (in program 9.5 the triangle is “laid on its side” - the sides of the triangle are: the first column and the main diagonal). Each number is equal to the sum of the two numbers above it. The rows of the triangle are symmetrical about the vertical axis and contain binomial coefficients.

#include using namespace std; int main() ( int n; cout<< "n = "; cin >>n; int pas[n][n]; for (int i = 0; i< n; i++) for (int j = 0; j < n; j++) pas[i][j] = 0; pas = 1; for (int i = 1; i < n; i++) { pas[i] = 1; for (int j = 1; j <= i; j++) { pas[i][j] = pas + pas[j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { cout.width(4); cout << pas[i][j]; } cout << "\n"; } return 0; } n = 12 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1

Questions
  1. Can a for loop instruction in a program be replaced by a while loop instruction? Can this always be done?
  2. When is it more convenient to use the for statement to organize loops? while?
  3. Are the following expressions possible in the head of a for statement: a) for (;a > b && !(a % 2);) b) for (a > b;;) c) for (;;i = 0) d) for ( ;i = 0;) e) for (;;i++, --b) f) for (--i;;) g) for (b = 0; b != a;) ?
  4. Variable i is a parameter of the outer loop, and variable j is a parameter of the nested loop. Will variable j be available in the outer loop? i in a nested loop?
Textbook
Homework
  1. Rear 29. Write a program that inputs natural numbers a And b, and the display shows all prime numbers in the range from a before b(algorithm idea Program 8.5)
  2. Rear 30. A number is called perfect if it is equal to the sum of all its divisors that are smaller than itself (for example, the number 6 = 1 + 2 + 3). Write a program that inputs a natural number N and determines whether N is a perfect number.
  3. Write a program that displays a square number table of size n x n, having the following form for n = 10: 1 * * * * * * * * * * 2 * * * * * * * * * * 3 * * * * * * * * * * 4 * * * * * * * * * * 5 * * * * * * * * * * 6 * * * * * * * * * * 7 * * * * * * * * * * 8 * * * * * * * * * * 9 * * * * * * * * * * 10
Literature
  1. Lafore R. Object-oriented programming in C++ (4th ed.). Peter: 2004
  2. Prata, Stephen. C++ programming language. Lectures and exercises, 6th ed.: Trans. from English - M.: LLC “I.D. William", 2012
  3. Lippman B. Stanley, Josie Lajoie, Barbara E. Mu. C++ programming language. Basic course. Ed. 5th. M: LLC “I. D. Williams”, 2014
  4. Elline A. C++. From lamer to programmer. St. Petersburg: Peter, 2015
  5. Shildt G. C++: Basic course, 3rd ed. M.: Williams, 2010



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 ..., operator brackets are used: 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 sample 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 must be accumulated in one of the variables, say m, and the second variable must " 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;

Note! 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 how it works, 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 composed 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 a 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 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 being 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 desired 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. there is a need 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 the 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.