When loops with precondition and postcondition are used. Loops with Conditions

Cycle while is called with a precondition, since the condition is checked before each execution of the loop body. It is used if the number of iterations of the loop is not known in advance.

Loop statement execution while starts by checking the condition. If it is true, then the statements of the body of the cycle are executed, then the condition is checked again, etc. As soon as it turns out that the condition is false at the next step, the execution of the cycle will end. Cycle while may never be executed if the condition at the very beginning is false.

In the block diagram, the cycle while depicted as shown in Fig. 5.3.

Rice. 5.3. Loop block diagram while

Entering a loop statement while is carried out similarly to the loop input for, after pressing the button while panels Programming The screen displays the items shown in Fig. 5.4. Enter the loop execution condition in the first field, and the loop body statements in the bottom field. If there is more than one statement in the loop body, then you need to use the button Add line for adding additional operators in the body of the loop.

Rice. 5.4. Inserting a loop statement while

The loop body must contain at least one statement that changes the loop condition so that the loop ends after a certain number of iterations, otherwise the loop will be executed indefinitely.

Example 5.4. Find the first negative term of a sequence

Flowchart of the algorithm for solving the example:

Example 5.5. Calculate function values when the argument changes X from -1 to 3 with a step of 0.5 and form a vector from these values y.

This problem has already been considered, but using the loop For, solve it with a cycle While.

Description and call of the function program:

Example 5.6. Find the number and sum of digits of a given natural number. Description and call of the function program:


This program uses two functions:

· mod- gives the remainder when divided x on y.

· trunc- returns the integer part z, removing the fractional part.

Example 5.7. Write a program to calculate the sum of the terms of an infinite series up to a term of the series.

In this case, the calculation of the current member of the series is performed according to the formula: is the current member of the series, - the previous member of the series .

An iterative process is a computational process in which the previous value of a variable is used to determine the next value of a variable. When using iterative processes, the method of successive approximations is implemented. The cycle is controlled by a given calculation error e. If at the next iteration the error ≥e, then the loop continues to calculate the next approximate value of the result, otherwise the loop exits.

Description and call of the function program:



Nested Loops

If the loop body is a cyclic structure, then such a loop is called nested or complex. A nested loop algorithm is an algorithm that contains a loop within which one or more other loops are nested.

The simplest case of nested loops is double. In this case, one loop is placed inside another. Various options for nested loops:

Example 6.1. Calculate .

Description and call of the function program:

The work of the nested loop is as follows: first, the first value of the parameter is set outer loop i, then control is transferred to the inner loop and the parameter of the inner loop j takes on all values ​​in turn. When the execution of the inner loop is completed, the second value of the outer loop parameter is set and the inner loop is completely executed again. The process is repeated until the parameter of the outer loop takes all the values.

Please pause AdBlock on this site.

Sometimes it is impossible to predict in advance how many times a loop should be executed. But at the same time, a certain condition is known when the cycle must stop. For example:

Program: Dice.

The program replaces the usual dice.

Control:

  • 1 - roll a die;
  • 0 - end the game.

Let's write a template for our game.

Listing 1.

#include #include #include int main(void) ( srand(time(NULL)); printf("########## Devil\"s bones ###########\n"); printf ("# #\n"); printf("# Commands: #\n"); printf("# #\n"); printf("# 1 - new game #\n"); printf("# 0 - exit #\n"); printf("# #\n"); printf("############################# ###########\n\n"); int control; int value = 0; printf("Enter command: "); scanf("%d", &control); if(control == 1)( value = 1 + rand()%6; printf("Result: %d\n", value); ) return 0; )

This is where we run into a problem. It is clear that it is impossible to know in advance when the game will end. This means that using the for loop directly will not work. One way out of this situation is to use other cyclic constructions. For example, a while loop.

Loop with while precondition

Listing 2.

While (condition) statement;

  1. The program encounters the keyword while , which means that the cyclic construction goes on;
  2. The condition is checked. Computed boolean expression, written in brackets;
  3. If the condition value is TRUE, then the body of the loop is executed. Go to point 2;
  4. If the condition value is FALSE, then the loop ends. Control is transferred to the statement following the loop body.

An operator is a single operator. If you need to execute several commands in a loop, then you must use the compound operator () .

Let's rewrite our program using this loop.

Listing 3.

#include #include #include int main(void) ( srand(time(NULL)); printf("########## Devil\"s bones ###########\n"); printf ("# #\n"); printf("# Commands: #\n"); printf("# #\n"); printf("# 1 - new game #\n"); printf("# 0 - exit #\n"); printf("# #\n"); printf("############################# ###########\n\n"); int control; int value = 0; printf("Enter command: "); scanf("%d", &control); while(control != 0)( switch(control)( case 1: value = 1 + rand()%6; printf("Result: %d\n", value); break; default: printf("Error! Try again...\ n"); break; ) printf("Enter command: "); scanf("%d", &control); ) printf("Good bye!\n"); return 0; )

Let's describe the algorithm of this program in words:

  1. We display the user's menu and a prompt to enter a command;
  2. We start the while loop. We check the condition;
  3. If the user enters 0 , then the loop execution condition becomes FALSE . The loop body is not executed. Control is transferred to the statement following the loop. The string Good bye! . The program ends;
    1. Select statement:
      1. If the user entered 1 , then we generate random number from 1 to 6 and display it on the screen. We exit the selection statement;
      2. If the user entered something else, we display an error message. Exit the select statement.
    2. We prompt the user to enter new team;
    3. We read the command code into the variable control ;
    4. We return to the condition check. Point 3.

The while loop is called a loop with a precondition, because before executing the body of the loop, the condition is checked. This means, for example, that it is possible that the body of the loop will not be executed at all even once. Another name for a while loop is a while loop. Literal translation from English. This name reflects the very essence of the cycle.

Mnemonic rule:

WHILE the condition is TRUE, execute the body of the loop.

Loop with do-while postcondition

And the last, third cyclic construction is the do-while loop.

This loop differs from the while loop in that the condition is checked not before the execution of the loop body, but after the execution of the loop body. This means that the body do-while loop must be executed at least once.

The syntax of this cyclic construction is as follows:

Listing 4.

Do statement; while (condition);

This construct works like this:

  1. The program encounters the do keyword. So before it is a do-while loop;
  2. The loop body is executed;
  3. The condition is checked;
  4. If the condition is TRUE, then the loop body is executed again;
  5. If the condition is FALSE, then the work of the cyclic construction is terminated. Programs are executed by the statement following the do-while loop.

Let's rewrite our program using of this type cyclic design.

Listing 5.

#include #include #include int main(void) ( srand(time(NULL)); printf("########## Devil\"s bones ###########\n"); printf ("# #\n"); printf("# Commands: #\n"); printf("# #\n"); printf("# 1 - new game #\n"); printf("# 0 - exit #\n"); printf("# #\n"); printf("############################# ###########\n\n"); int ch_control; int value = 0; do ( printf("Input command: "); scanf("%d", &ch_control); switch(ch_control )( case 0: break; case 1: value = 1 + rand()%6; printf("Result: %d\n", value); break; default: printf("Error! Try again...\n "); break; ) )while(ch_control != 0); printf("Good bye!\n"); return 0; )

In general, it is very similar to the previous code. True, I had to change the selection operator a little: add the case 0: branch there. Otherwise, due to the fact that the check is performed after the execution of the loop body, the program worked incorrectly. Entering zero resulted in an error message. In the previous program (with the while loop) there could not be such a situation, because equality to zero was checked in the loop condition. If zero was entered, the condition would become false, which means the loop would end and the loop body would not be executed.

Tags: C cycles. C loops. Loop with postcondition. Loop with precondition. Cycle with a brush. while. do while. for. break. continue

Introduction. Loops with a precondition.

When solving practical problems, the need constantly arises to repeat the action a given number of times, or until a certain condition is reached. For example, display a list of all users, tile the plane with a texture, perform calculations on each element of the data array, etc. In C, three types of loops are used for this purpose: with precondition, postcondition and cycle for with a counter (although this is a conditional name, because there may not be a counter).

Any loop consists of a body and a condition check under which this loop should be terminated. The loop body is the set of instructions to be repeated. Each iteration of the loop is called an iteration.

Consider a loop with a precondition.

Int i = 0; while (i< 10) { printf("%d\n", i); i++; }

This loop is executed as long as the condition given after keyword while. The body of the cycle is two lines, one displays a number, the second changes it. Obviously, this loop will be executed 10 times and will display
0
1
2
3
and so on up to 9.

It is very important that the exit condition of the loop is ever fulfilled, otherwise a loop will occur and the program will not terminate. For example

Int i = 0; while (i< 10) { printf("%d\n", i); }

This loop does not change the variable i, which is used to define the stop condition, so the loop will not end.

Int i = 0; while (i > 0) ( printf("%d\n", i); i++; )

In this program, the loop will, of course, end, but due to the wrong action, it will be executed much more than 10 times. Since C doesn't monitor variable overflow, you will have to wait until the variable overflows and becomes less than zero.

int i; while (i< 10) { printf("%d\n", i); i++; }

This example has undefined behavior. Since the variable i is not initialized in advance, it stores garbage, a previously unknown value. With different contents of the variable i, the behavior will change.

If the body of the while loop contains a single statement, then the curly braces can be omitted.

Int i = 0; while (i< 10) printf("%d\n", i++);

Here we are incrementing the variable i when calling the printf function. This coding style should be avoided. The absence of curly braces, especially at the beginning of learning, can lead to errors. In addition, the code is less readable, and the extra parentheses don't make the listings much bigger.

Loops with a postcondition.

A loop with a postcondition differs from a while loop in that the condition in it is checked after the loop is executed, that is, this loop will be repeated at least once (unlike the while loop, which may not be executed at all). Loop Syntax

Do (loop body) while(condition);

The previous example using a do loop would look like

Int i = 0; do ( printf("%d\n", i); i++; ) while(i< 10);

Let's look at an example of using a loop with a postcondition and a precondition. Let us need to integrate a function.

Rice. 1 Numerical integration of a function∫ a b f x d x

An integral is a sum of infinitesimals. We can represent the integral as a sum, and simply replace infinitesimal values ​​with small values.

∫ a b f x d x = ∑ i = a b f i h

It can be seen from the formula that we actually divided the area under the graph into many rectangles, where the height of the rectangle is the value of the function at the point, and the width is our step. By adding the areas of all the rectangles, we thereby obtain the value of the integral with some error.

left rectangles" src="/images/c_loop_rectangles_left.png" alt="Numerical integration of a function by the method
left rectangles"> Рис. 2 Численное интегрирование функции методом!}
left rectangles

Let the required function be x 2 . We will need the following variables. First, the sum accumulator to store the integral. Secondly, the left and right borders of a and b, and thirdly, the step h. We also need the current value of the x function argument.

To find the integral, it is necessary to pass from a before b with some step h, and add to the sum the area of ​​a rectangle with sides f(x) and h.

#include #include int main() ( double sum = 0.0; double a = 0.0; double b = 1.0; double h = 0.01; double x = a; while (x< b) { sum += x*x * h; x += h; } printf("%.3f", sum); getch(); }

The program outputs 0.328.

∫ 0 1 x 2 d x = x 3 3 | 0 1 = 1 3 ≈ 0.333

If you look at the graph, you can see that each time we find the value of the function at the left point. Therefore, this method of numerical integration is called the method of left rectangles. Similarly, you can take the right value. Then it will be the right rectangles method.

While(x< b) { x += h; sum += x*x * h; } right rectangles" src="/images/c_loop_rectangles_right.png" alt="Numerical integration of a function by the method
right rectangles"> Рис. 3 Численное интегрирование функции методом!}
right rectangles

The sum in this case will be equal to 0.338. The left and right rectangle method is not very accurate. We actually approximated (approached) a smooth graph of a monotonically increasing function with a histogram. If you think a little, then the approximation can be carried out not only by summing rectangles, but also by summing trapezoids.

trapezium" src="/images/c_loop_integral_trapezium.png" alt="Numerical integration of a function by the method
trapezoid"> Рис. 4 Численное интегрирование функции методом!}
trapezoid

The trapezoidal approximation is actually a piecewise approximation by first-order curves (ax+b). We connect the points on the graph using line segments. It can be complicated by connecting the points not with segments, but with pieces of a parabola, then it will be Simpson's method. If we complicate it further, then we will come to spline interpolation, but this is another, very long conversation.

Let's get back to our sheep. Consider 4 cycles.

Int i = 0; while (i++< 3) { printf("%d ", i); } int i = 0; while (++i < 3) { printf("%d ", i); } int i = 0; do { printf("%d ", i); } while(i++ < 3); int i = 0; do { printf("%d ", i); } while(++i < 3);

If you run these examples, you will see that the loops are executed from two to four times. This is worth paying attention to, because incorrectly changing the loop counter often leads to errors.

It often happens that we need to exit a loop without waiting for some flag to be raised or the value of a variable to change. For this purpose, the operator break, which causes the program to exit the current loop.

Let's solve a simple problem. The user enters numbers until the number 0 is entered, after which it outputs the largest of those entered. There is one catch here. How many numbers the user will enter is not known. Therefore, we will create an infinite loop, and we will exit it using the operator break. Inside the loop, we will receive data from the user and select the maximum number.

#include #include int main() ( int num = 0; int max = num; printf("To quit, enter 0\n"); /*infinite loop*/ while (1) ( printf("Please, enter number: "); scanf("%d", &num); /*loop exit condition*/ if (num == 0) ( break; ) if (num > max) ( max = num; ) ) printf("max number was %d ", max); getch(); )

Let me remind you that there is no special Boolean type in C. Numbers are used instead. Zero is false, all other values ​​are true. The while(1) loop will run indefinitely. The only exit point from it is the condition

If(num == 0)

In this case, we exit the loop with break; To begin with, we set 0 as the maximum. The user enters a number, after which we check whether it is zero or not. If it is not zero, then we compare it with the current maximum.

Infinite loops are used quite often, since the input data is not always known in advance, or they can change during the program.

When we need to skip the body of the loop, but at the same time continue the execution of the loop, the operator is used continue. A simple example: the user enters ten numbers. Find the sum of all the positive numbers he entered.

#include #include int main() ( int i = 0; int positiveCnt = 0; float sum = 0.0f; float input; printf("Enter 10 numbers\n"); while (i< 10) { i++; printf("%2d: ", i); scanf("%f", &input); if (input <= 0.0) { continue; } sum += input; positiveCnt++; } printf("Sum of %d positive numbers = %f", positiveCnt, sum); getch(); }

The example seems somewhat far-fetched, although in general it reflects the meaning of the operator continue. In this example, the variable positiveCnt is a counter of positive numbers, sum amount, and input- a temporary variable for entering numbers.

Here is another example. It is required that the user enter an integer greater than zero and less than 100. Until the required number is entered, the program will continue to poll.

Do ( printf("Please, enter number: "); scanf("%d", &n); if (n< 0 || n>100) ( printf("bad number, try again\n"); continue; ) else ( break; ) ) while (1);

for loop

One of the most used is the counter loop. for. Its syntax

For (<инициализация>; <условие продолжения>; <изменение счётчика>){ <тело цикла> }

For example, let's print the squares of the first hundred numbers.

int i; for (i = 1; i< 101; i++) { printf("%d ", i*i); }

One of the great things about the for loop is that it can work with more than just integers.

float num; for (num = 5.3f; num > 0f; num -= 0.2) ( printf("%.2f ", num); )

This loop will output numbers from 5.3 to 0.1. The for loop may not have some "blocks" of code, for example, there may be no initialization, no check (then the loop becomes infinite), or a change in the counter. Here is an integral example implemented using a counter for

#include #include int main() ( double sum = 0.0; double a = 0.0; double b = 1.0; double h = 0.01; double x; for (x = a; x< b; x += h) { sum += x*x * h; } printf("%.3f", sum); getch(); }

Let's look at a piece of code

Double x ; for (x = a; x< b; x += h) { sum += x*x * h; }

It can be changed like this

Double x = a; for(; x< b; x+=h) { sum += x*x*h; }

Moreover, using the operator break, you can remove the condition and write

double x; for (x = a;; x += h)( if (x>b)( break; ) sum += x*x*h; )

Double x = a; for (;;)( if (x > b)( break; ) sum += x*x*h; x += h; )

in addition, using the "," operator, you can transfer part of the actions

Double x ; for (x = a; x< b; x += h, sum += x*x*h) ;

NOTE: Although it is possible to do this, please do not do this! This worsens the readability of the code and leads to subtle bugs.

Let's solve some practical problem more difficult. Let us have a function f(x). Find the maximum of its derivative on the segment. How to find the derivative of a function numerically? Obviously, by definition). The derivative of a function at a point is the tangent of the slope of the tangent.

Fx′ = dxdy

Let's take a point on the curve with coordinates (x; f(x)), move forward one step h, get the point (x+h, f(x+h)), then the derivative will be

D x d y = f (x + h) - f x (x + h - x) = tg α

That is, the ratio of the small increment of the function to the small increment of the argument. The attentive reader may wonder why we are moving forward in a function and not backward. Well let's go back

D x d y = f x - f (x - h) h = tg β

Taking the average of these two values, we get

F (x + h) - f (x - h) 2h

In general, now the task becomes trivial: we go from the point a to the point b and find the minimum value of the derivative, as well as the point at which the derivative takes this value. For the solution, we need, as in the problem with the integral, variables for the boundaries of the search area a and b, present value x and step h. In addition, the maximum value maxVal and coordinate maxX this maximum value. To work, take the function x sin x

#include #include #include int main() ( double a = 0; double b = 3.0; double h = 0.001; double h2 = h * 2.0; double maxVal = a*sin(a); double maxX = a; double curVal; double x; // We go through the entire area from a to b // and look for the maximum of the first derivative // ​​Use the function x*sin(x) for (x = a; x< b; x += h) { curVal = ((x+h)*sin(x+h)-(x-h)*sin(x-h))/h2; if (curVal >maxVal) ( maxVal = curVal; maxX = x; ) ) printf("max value = %.3f at %.3f", maxVal, maxX); getch(); )

At the output, the program issues max value = 1.391 at 1.077

The numerical solution gives the same results (up to an error) as our program.

Nested Loops

Consider an example where loops are nested inside each other. Let's get the multiplication table.

#include #include #include int main() ( int i, j; // For each i for (i = 1; i< 11; i++) { // Выводим строку из произведения i на j for (j = 1; j < 11; j++) { printf("%4d", i*j); } // После чего переходим на newline printf("\n"); ) getch(); )

In this example, in the first loop over the variable i nested second loop over variable j. The sequence of actions is as follows: first we enter the loop for i, then for the current i Numbers are displayed 10 times in a row. After that, you need to move to a new line. Now let's display only the elements under the main diagonal

For (i = 1; i< 11; i++) { for (j = 1; j < 11; j++) { if (j >i) ( break; ) printf("%4d", i*j); ) printf("\n"); )

As you can see, the operator break allows you to exit only the current loop. This example could be rewritten like this

For (i = 1; i< 11; i++) { for (j = 1; j <= i; j++) { printf("%4d", i*j); } printf("\n"); }

In this case, we use the counter of the first loop in the nested loop.

Ru-Cyrl 18-tutorial Sypachev S.S. 1989-04-14 [email protected] Stepan Sypachev students

Still not clear? - write questions to the box

Hello dear readers! Here we come to the study of cycles. Cycles in Pascal. What it is? How to use it? What are they needed for? These are the questions I will answer today.
If you have read, then you know that there are three types of algorithms: linear, branching and cyclic. We already know how to implement algorithms in Pascal. Let's start studying the last type of algorithms.
In Pascal, as in most programming languages, there are three types of looping constructs.

Any cycle consists of a body and a header. The loop body is a set of repeating statements, and the condition is a logical expression, depending on the result of which the loop is repeated.

Let's take one problem, which we will solve using various types of cycles.

Task 1. Display all numbers from 1 to the number entered from the keyboard.

While, or a loop with a precondition

As you probably already understood from the name, while is a loop in which the condition comes before the body. Moreover, the loop body is executed if and only if the condition true; as soon as the condition becomes false

While has the format:

while < условие> do<оператор 1>; (Bye…do….)

This loop is suitable for only one statement, if you want to use multiple statements in your code, you should enclose them in statement brackets − begin and end;.

The solution of the problem.

Program example_while; var i, N: integer; (declaring variables) begin i:= 1; ( Set i to 1 ) readln(N); (Read the last number) while i<= N do {Как только i станет больше N, цикл прекратится (можно было бы написать просто <, но пришлось бы добавлять 1 к N) } begin {Открываем операторные скобки} write(i, " "); {Выводим i} Inc(i); {увеличиваем i на один.} end; { закрываем скобки } end.

Repeat, or a loop with a postcondition

Repeat- complete opposite while. Repeat is a loop in which the condition is after the body. Moreover, it is executed if and only if the result of the condition false;as soon as the boolean expression becomes true, the loop is terminated.

Repeat has the format:

repeat( repeat … )
<оператор 1>;
< оператор 2>;

until(before…) <условие>

Begin and end not required.

The solution of the problem.

Program example_repeat; var i, N: integer;( declare variables) begin i:= 1; ( Set i to 1 ) readln(N); ( Read last number ) repeat ( no need for begin and end after repeat ) write(i, " "); (Display i) Inc(i); (Increase i by one.) until i = N + 1; (For example, i = 11 and N = 10. The loop will stop, so the condition becomes true.) end.

For, or a loop with a parameter

For is a loop in which the body is executed a given number of times.

There are two ways to write this loop:

First form

for<счетчик1> := <значение1>to<конечное_значение>do<оператор1>;

<счетчик1>will increase by 1.

<значение1>is the initial value of the counter. It can be a variable or a number.
<конечное_значение>: as soon as the value<счетчик1>will become more<конечное_значение>

If you want to write several statements in the loop body, use begin and end.

And<счетчик1>, and<конечное_значение>, and<значение1>- variables the whole type.

Most often, the variable i is used as a counter.

Second form

for<счетчик2> := <значение2>downto<конечное_значение>do<оператор1>;

After each iteration, the value<счетчик2>will decrease by 1.

<значение2>is the initial value of the counter.
<конечное_значение>: as soon as the value<счетчик2>will become less<конечное_значение>, the loop is terminated.

Two important notes:

  1. The loop repeats as long as the value of the counter lies in the segment [value; end_value].
  2. Change the value of the counter inside the body it is forbidden! Here is what the compiler outputs:

The solution of the problem:

Program example_for; var i, N: integer; begin read(N); (suppose we entered 10) for i:= 1 to N do write(i, " "); (number of iterations - 10 - 1 + 1 = 10) end.

Agree, this code is simpler and more concise than all the previous ones. And cycle for- not quite an ordinary cycle, there is no logical condition in it. Therefore, a loop with a parameter in programming is called syntactic sugar. Syntactic sugar is an addition to the syntax of a programming language that does not add new features, but makes the language more human-friendly to use.

Let's solve a couple of problems.

For1. Integers K and N (N > 0) are given. Output N times the number K.

We organize a simple cycle from 1 to the required number.

Program for1; var K, N, i: integer; begin read(K, N); for i:= 1 to N do write(K, " "); (We write K separated by a space) end.

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

Since A< B, то цикл должен будет выводить все числа от А до B. Чтобы сосчитать количество чисел, используем формулу: <конечное_значение> — <начальное_значение> + 1.

Program for2; var A, B, i, count: integer; begin read(A, B); for i:= A to B do write(i, " "); (write numbers from smallest to largest) count:= B - A + 1; (count number of numbers) writeln; write("Number of numbers - ", count); end.

For9. Given two integers A and B (A< B). Найти сумму квадратов всех целых чисел от A до B включительно.

We organize the same cycle as in the previous problem, but at the same time sum the squares of all numbers. To calculate the square, use the function.

Program for9; var A, B, i, S: integer; begin read(A, B); S:= 0; (PascalABC does this automatically, but if you have a different compiler we advise you to set the variables to zero manually) for i:= A to B do S:= S + Sqr(i); (add all squares) writeln; write("Sum of squares - ", S); end.

For13°. An integer N (> 0) is given. Find the value of the expression 1.1 - 1.2 + 1.3 - ... (N terms, signs alternate). Conditional operator do not use.

In order to change the sign, each iteration of the loop we change the value of the special variable to the opposite.

Program for13; var N, A, i: integer; S: real begin Write("N = "); readln(N); S:= 1.1; A:= 1; (Positive first) for i:= 2 to N do (we have already done the first iteration of the loop, so we start counting from 2) begin A:= -A; (Now negative) S:= S + A * (1 + i / 10); (add) end; WriteIn(S:5:1); (Let's give one familiarity for the fractional part) end.

While1°. Positive numbers A and B (A > B) are given. On a segment of length A, the maximum possible number of segments of length B (without overlaps) is placed. Without using multiplication and division, find the length of the unoccupied part of segment A.

Each time subtract B from A until A - B >= 0.

Program while1; var A, B: integer; begin readln(A, B); while (A - B) >= 0 do A:= A - B; (While the difference is positive, we subtract. It is necessary to provide a variant with a multiplicity of A and B, therefore >=) write(A); end.

While4°.An integer N (> 0) is given. If it is a power of 3, then output True, if not, output False.

We act as follows: while N is divisible by 3, we divide N by 3. Then, if N = 1, the number is a power of three; if N<>1, then the number is not a power of three. In order to solve this problem, you need to know what is and how they work.

Program while4; var N: integer; begin readln(N); while N mod 3 = 0 do N:= N div 3; (As long as the remainder of division by three is zero, divide N by 3) writeln(N = 1); (boolean expression) end.

That's all for today! Do not forget to visit our site more often and click on the buttons that are located in front of the comments.

A cyclic computational process (CPC) is characterized by repeating the same calculations over a certain set of data. The number of iterations of the loop is controlled by a special variable called it counter or control variable cycle. A condition is imposed on the counter that determines how long the loop should be executed.

The repeatable block of calculations is called body cycle. The body of the loop must provide change counter value so that it can complete. If the loop body consists of more than one statement, it enclosed in operator brackets begin ... end;. Executing the body of the loop once is called it step.

Thus, to program a loop, it suffices to define a condition that controls the number of iterations and describe the statements that form the body of the loop. From this point of view, only two types of loops are theoretically possible - the condition check either precedes the execution of the loop body, or occurs after it. Let's depict these cycles in the form of block diagrams with the corresponding descriptions:

Loop with precondition: the condition is checked first, then, depending on whether it is true or false, either the loop body is executed, or the transition to the statement following the loop body follows. After the loop body is completed, control is again transferred to the condition test. Naturally, it is assumed that some change in the variables included in the condition was provided in the loop body - otherwise, looping and the program will hang.

Loop with postcondition: the body of the loop is executed first, then control is transferred to the condition test. Depending on the truth or falsity of the condition, the body of the loop is executed repeatedly or there is a transition to the statement following the body of the loop. Everything said about possible looping for a loop with a precondition is also true for a loop with a postcondition.

Based on the above block diagrams, the main difference between the two cycles is obvious: a loop with a postcondition is guaranteed to be executed at least once, while a loop with a precondition may never be executed if the condition is immediately false.

Pascal implements both types of loops. A loop with a precondition has the following general form:

while boolean_expression do begin

(loop body statements)

The work of the cycle can be described in words: " while the logical expression is true, the body of the loop is repeated".

The logical expression is built according to the rules studied in Chapter 7. The loop body can be formed by any Pascal operators. If there is only one operator in the body of the loop, the operator brackets can be omitted.

The general notation for a cycle with a postcondition is as follows:

(loop body statements)

until boolean_expression;

The postcondition loop works like this: the body of the loop is repeated until the boolean expression evaluates to true". Note that, unlike while, Pascal's repeat loop works as long as the condition false. This difference is emphasized by the use of the keyworduntil("until not") instead of while("until"). Also, as an exception, the repeat loop body, even if it consists of several statements, can be not enclose in operator brackets.

Quite often, cycles are interchangeable. Imagine, for example, that for each of the values ​​of the variable x=1,2,…,20, you need to perform some calculation (mathematically, this law of change in x can be written as
or
). Let's show the general form of while and repeat loops:

while x<=20 do begin

(calculation operators)

(calculation operators)

As you can see from the listing, the control variable x in both cases is assigned the initial value 1, both loops change the value of x and, accordingly, the loop condition by the operator x:=x+1;, but for the repeat loop, the condition is "reversed" ("until x becomes more than 20"), and the body is not enclosed in operator brackets.

Often the use of one of the loops looks preferable. For example, processing user input from the keyboard is more convenient with the help of repeat (first the user must press a key, then checks and processing follow).

Share