A loop with a precondition is as follows. Cycles. The importance of loops in programming

Loop with precondition

Cycle- a kind of control structure in high-level programming languages, designed to organize the repeated execution of a set of instructions. Also, a loop can be called any sequence of instructions repeatedly executed, organized in any way (for example, using a conditional jump).

Definitions

A sequence of instructions designed to be executed repeatedly is called body of the cycle... Executing the loop body once is called iteration... The expression that determines whether the iteration will be executed again, or the loop will end, is called exit condition or the condition for the end of the cycle(or condition of continuation depending on how its truth is interpreted - as a sign of the need to complete or continue the cycle). The variable storing the current iteration number is called iteration counter cycle or just cycle counter... The loop does not necessarily contain a counter, the counter does not have to be one - the condition for exiting the loop can depend on several variables changed in the loop, or it can be determined by external conditions (for example, the onset of a certain time), in the latter case, the counter may not be needed at all.

Execution of any loop includes initial initialization of the loop variables, checking the exit condition, executing the loop body, and updating the loop variable at each iteration. In addition, most programming languages ​​provide means for early termination of the loop, that is, exit from the loop regardless of the truth of the exit condition.

Types of cycles

Unconditional loops

Sometimes programs use loops, the exit from which is not provided by the logic of the program. Such cycles are called unconditional, or endless. Due to their atypical nature, programming languages ​​do not provide special syntactic tools for creating infinite loops, therefore, such loops are created using constructions designed to create ordinary (or conditional) cycles. To ensure infinite repetition, the condition check in such a loop is either absent (if the syntax allows, as, for example, in the loop LOOP… END LOOP language of Ada), or is replaced by a constant value ( while true do ... in Pascal).

Loop with precondition

A loop with a precondition is a loop that is executed as long as a certain condition specified before its beginning is true. This condition is checked before execution of the loop body, so the body may not be executed even once (if the condition is false from the very beginning). In most procedural programming languages, it is implemented by the operator while, hence its second name - while-loop.

Loop with postcondition

Loop with postcondition - a loop in which the condition is checked after execution of the loop body. It follows that the body always executed at least once. In Pascal, this loop is implemented by the repeat..until statement; in C, do ... while.

There are differences in the interpretation of a loop condition with a postcondition in different languages. In Pascal and the languages ​​derived from it, the condition of such a cycle is interpreted as exit condition(the cycle ends when the condition is true, in Russian terminology such cycles are also called "cycle before"), and in C and its descendants - as continuation condition(the loop ends when the condition is false, such loops are sometimes called "while loop") ... ..

Loop with an exit from the middle

A loop out of the middle is the most common form of a conditional loop. Syntactically, such a loop is formatted using three constructs: the beginning of the loop, the end of the loop, and the command to exit the loop. The start construct marks the point in the program where the body of the loop begins, and the end construct marks the point where the body ends. Inside the body, there must be a command to exit the loop, when executed, the loop ends and control is transferred to the statement following the end of the loop construction. Naturally, for the loop to be executed more than once, the exit command should not be called unconditionally, but only when the loop exit condition is met.

The fundamental difference between this type of loop and those considered above is that the part of the loop body located after the beginning of the loop and before the exit command is always executed (even if the loop exit condition is true at the first iteration), and the part of the loop body located after the exit command is not executed on the last iteration.

It is easy to see that using a loop with an exit from the middle, you can easily model both a loop with a precondition (by placing an exit command at the beginning of the loop body) and a loop with a postcondition (by placing an exit command at the end of the loop body).

Some programming languages ​​contain special constructs for organizing a loop with an exit from the middle. So, in the language of Ada, the construction is used for this LOOP… END LOOP and the exit command EXIT or EXIT WHEN:

LOOP ... Part of the body of the EXIT WHEN loop<условие выхода>; ... Body part of the IF loop<условие выхода>THEN EXIT; END; ... Body part of the END LOOP loop:

Here, inside the loop, there can be any number of exit commands of both types. The exit commands themselves are not fundamentally different, usually EXIT WHEN used when only the exit condition is checked, but simply EXIT- when the loop is exited in one of the variants of a complex conditional operator.

In languages ​​where such constructs are not provided, a loop with an exit from the middle can be modeled using any conditional loop and an early exit operator (such as break in C), or the unconditional jump operator goto.

Cycle with counter

A loop with a counter is a loop in which a variable changes its value from a given one initial value to the final value with some step, and for each value of this variable, the body of the loop is executed once. In most procedural programming languages, it is implemented by the operator for, which indicates the counter (the so-called "cycle variable"), the required number of passes (or the limit value of the counter) and, possibly, the step with which the counter changes. For example, in the Oberon-2 language, such a cycle looks like:

FOR v: = b TO e BY s DO... the body of the loop END

(here v is the counter, b is the initial value of the counter, e is the limit value of the counter, s is the step).

The question about the value of the variable at the end of the loop, in which this variable was used as a counter, is ambiguous. For example, if a Pascal program contains a construction of the form:

I: = 100; for i: = 0 to 9 do begin ... loop body end; k: = i;

the question arises: what value will be eventually assigned to the variable k: 9, 10, 100, maybe something else? What if the cycle ends ahead of schedule? The answers depend on whether the counter value is incremented after the last iteration and whether the translator changes this value additionally. Another question: what happens if a new value is explicitly assigned to the counter inside the loop? Different programming languages ​​solve these issues in different ways. In some, the behavior of the counter is clearly regulated. In others, for example, in the same Pascal, the language standard does not define either the final value of the counter, or the consequences of its explicit change in the loop, but does not recommend changing the counter explicitly and using it at the end of the loop without reinitialization. A Pascal program that ignores this recommendation may produce different results when executed on different systems and using different translators.

The question in the language of Ada has been radically resolved: the counter is considered described in the heading of the cycle, and outside of it simply does not exist. Even if the name of the counter is already used in the program, a separate variable is used as the counter inside the loop. It is forbidden to explicitly assign any values ​​to the counter; it can only be changed by the internal mechanism of the loop operator. As a result, the construction

I: = 100; for i in (0 ..9) loop ... loop body end loop; k: = i;

externally similar to the above cycle in Pascal, it is interpreted unambiguously: the variable k will be assigned the value 100 because the variable i used outside of this loop has nothing to do with the counter i, which is created and modified within the loop. It is believed that such separation of the counter is the most convenient and safe: no separate description is required for it and the probability of random errors associated with accidental destruction of variables external to the cycle is minimal. If a programmer needs to include a loop with a counter in the finished code, then he may not check whether a variable exists with the name that he has chosen as a counter, not add a description of a new counter to the header of the corresponding procedure, not try to use one of the existing ones, but in this moment of "free" counters. He simply writes a loop with a counter variable, the name of which is convenient for him, and can be sure that no name collision will occur.

A cycle with a counter can always be written as a conditional cycle, before the start of which the counter is assigned an initial value, and the exit condition is when the counter reaches its final value; in this case, an operator for changing the counter by a given step is added to the body of the cycle. However, special operators of a cycle with a counter can be translated more efficiently, since the formalized form of such a cycle allows the use of special processor instructions for organizing cycles.

In some languages, for example, C and others descended from it, the cycle for despite the syntactic form of a counter loop, it is actually a preconditioned loop. That is, in C, the loop construct is:

For (i = 0; i< 10 ; ++i) { ... тело цикла }

actually represents a different form of notation for the construction:

I = 0; while (i< 10 ) { ... тело цикла ++i; }

That is, in the design for first, an arbitrary statement of initialization of the loop is written, then a continuation condition, and, finally, a certain operation performed after each body of the loop (this does not have to be a change in the counter; it can be a pointer edit or some completely extraneous operation). For languages ​​of this kind, the problem described above can be solved very simply: the counter variable behaves completely predictably and after the end of the loop it retains its last value.

Nested loops

It is possible to organize a loop inside the body of another loop. Such a cycle will be called nested loop... The nested cycle in relation to the cycle in the body of which it is nested will be named inner loop, and vice versa, a loop in the body of which a nested loop exists will be named external in relation to the nested. Inside the nested loop, one more loop can be nested in turn, forming the following nesting level etc. The number of nesting levels is usually not limited.

The total number of executions of the inner loop body does not exceed the product of the number of iterations of the inner and all outer loops. For example, taking three nested loops, each with 10 iterations, we get 10 executions of the body for the outer loop, 100 for the second-level loop, and 1000 in the innermost loop.

One of the problems associated with nested loops is organizing early exit from them. Many programming languages ​​have an early loop termination operator ( break in Xi, exit in Turbo Pascal, last in Perl, etc.), but it usually only exits the loop at the level it was called from. Calling it from a nested loop will terminate only this inner loop, while the enclosing loop will continue to execute. The problem may seem far-fetched, but it does sometimes arise when programming complex data processing, when an algorithm requires an immediate interruption under certain conditions, the presence of which can only be checked in a deeply nested loop.

There are several solutions to the problem of exiting nested loops.

  • The simplest is to use the unconditional jump operator goto to exit to the point in the program immediately following the nested loop. This option is criticized by supporters structured programming, like all designs requiring the use of goto... Some programming languages, for example Modula-2, simply do not have an unconditional jump operator, and such a construction is impossible in them.
  • An alternative is to use staff funds completion of cycles, if necessary, setting special flags that require immediate completion of processing. The disadvantage is the complication of the code, decrease in performance without any advantages, except for theoretical "correctness" due to the rejection of goto.
  • Placing a nested loop in a procedure. The idea is that all action that may need to be interrupted early should be formalized as a separate procedure, and for early termination, use the procedure exit operator (if there is one in the programming language). In C, for example, you can build a function with a nested loop, and organize the exit from it using the operator return... The disadvantage is that the allocation of a code fragment into a procedure is not always logically justified, and not all languages ​​have standard means of early completion of procedures.
  • Take advantage of the mechanism for generating and handling exceptions (exceptions), which is now available in most Java. In this case, in an abnormal situation, the code in the nested loop raises an exception, and the exception handling block, which contains the entire nested loop, intercepts and processes it. The disadvantage is that the implementation of the exception handling mechanism in most cases is such that the speed of the program is reduced. True, in modern conditions this is not particularly important: in practice, the performance loss is so small that it matters only for very few applications.
  • Finally, there are language-specific tools for breaking out of nested loops. So, in the Ada language, the programmer can mark the cycle ( top level nested loop) with a label, and specify this label in the command for early termination of the loop. The exit will occur not from the current loop, but from all nested loops up to the marked one, inclusive.

Joint cycle

Another version of the loop is a loop that specifies the execution of some operation for objects from a given set, without explicitly specifying the order in which these objects are enumerated. Such cycles are called joint(and loops through the collection, view cycles) and represent a formal record of an instruction of the form: "Perform operation X for all elements included in the set M". The joint loop, in theory, does not in any way determine in what order the operation will be applied to the elements of a set, although specific programming languages, of course, can specify a specific order of iterating over the elements. Arbitrariness makes it possible to optimize the execution of the cycle by organizing access not in a given programmer, but in the most advantageous order. If there is a possibility of parallel execution of several operations, it is even possible to parallelize the execution of a joint loop, when the same operation is simultaneously performed on different computational modules for different objects, while the program remains logically sequential.

}

Also, a loop can be any sequence of instructions that can be executed repeatedly, organized in any way. Definitions A sequence of instructions intended for repeated execution is called the body of a loop. A single execution of a loop body is called an iteration. The defining expression will iterate again or the loop will end is called an exit condition, or a loop termination condition, or a continuation condition, depending on how its truth is interpreted as a sign of necessity ...


Share your work on social media

If this work did not suit you at the bottom of the page there is a list of similar works. You can also use the search button


Cycle - a kind of control structure inhigh-level programming languages, intended for the organization of multiple execution of the set instructions ... Also, a loop can be called any sequence of instructions repeatedly executed, organized in any way.

Definitions

A sequence of instructions designed to be executed repeatedly is called body of the cycle ... A single execution of the loop body is called iteration. Expression determining whether the iteration will be executed again, or the loop will end, is called exit condition or the condition for the end of the cycle(or condition of continuationdepending on how its truth is interpreted - as a sign of the need to complete or continue the cycle). Variable storing the current iteration number is callediteration countercycle or just cycle counter ... The loop does not necessarily contain a counter, the counter does not have to be one - the condition for exiting the loop can depend on several variables changed in the loop, or it can be determined by external conditions (for example, the onset of a certain time), in the latter case, the counter may not be needed at all.

Execution of any loop includes initial initialization of the loop variables, checking the exit condition, executing the loop body, and updating the loop variable at each iteration. In addition, most programming languages ​​provide means for early control of the loop, for example, operators to terminate the loop, that is, to exit the loop regardless of whether the exit condition is true.

Loop with precondition

A loop with a precondition is a loop that is executed as long as a certain condition specified before its beginning is true. This condition is checked before execution of the loop body, so the body may not be executed even once (if the condition is false from the very beginning). In most procedural programming languages, it is implemented by the operator while , hence its second name - while-loop. On Pascal a loop with a precondition looks like this:

while<условие>do

begin

<тело цикла>

end;

Loop with postcondition

Loop with postcondition - a loop in which the condition is checked after execution of the loop body. It follows that the bodyalways executedat least once. In Pascal, this loop implements operator repeat..until; in C, do ... while.
In Pascal, a postcondition loop looks like this:

repeat

<тело цикла>

until <условие выхода>

Loop with an exit from the middle

A loop out of the middle is the most common form of a conditional loop. Syntactically, such a loop is formatted using three constructs: the beginning of the loop, the end of the loop, and the command to exit the loop. The start construct marks the point in the program where the body of the loop begins, and the end construct marks the point where the body ends. Inside the body, there must be a command to exit the loop, when executed, the loop ends and control is transferred to the statement following the end of the loop construction. Naturally, for the loop to be executed more than once, the exit command should not be called unconditionally, but only when the loop exit condition is met.

actually this is break;

Cycle with counter

A cycle with a counter is a cycle in which some variable changes its value from the given initial value to the final value with some step, and for each value of this variable the body of the loop is executed once. In most procedural programming languages, it is implemented by the operator for , which indicates the counter (the so-called "cycle variable"), the required number of passes (or the limit value of the counter) and, possibly, the step with which the counter changes.

for i: = 0 to 9 do

begin

Loop body

end;

Early exit from the cycle

An early exit command is used when it is necessary to interrupt the execution of a cycle in which the exit condition has not yet been reached. This happens, for example, when an error is detected during the execution of the loop body, after which further work of the loop is meaningless.

The early exit command is usually called EXIT or break , and its action is similar to the action of the unconditional jump command ( goto ) to the command immediately following the loop within which this command is located.

Nested loops

It is possible to organize a loop inside the body of another loop. Such a cycle will be callednested loop... The nested cycle in relation to the cycle in the body of which it is nested will be namedinner loop, and vice versa, a loop in the body of which a nested loop exists will be named external in relation to the nested. Inside the nested loop, one more loop can be nested in turn, forming the followingnesting leveletc. The number of nesting levels, as a rule, is not limited.

The total number of executions of the inner loop body does not exceed the product of the number of iterations of the inner and all outer loops. For example, taking three nested loops, each with 10 iterations, we get 10 executions of the body for the outer loop, 100 for the second-level loop, and 1000 in the innermost loop.

Other similar works that may interest you. Wshm>

2740. Cyclic algorithms. Loop with precondition 16.37 KB
Let's get acquainted with the first of them - the loop operator with the while precondition. Loops with a precondition are used when the execution of the loop is associated with some logical condition. A loop statement with a precondition has two parts: a loop execution condition and a loop body. The general form of notation is the following while condition do begin loop body end; In Russian it sounds something like this: while this condition is met, do a group of operators from the beginning to the end; It is quite clear that the operator brackets are used to separate that from the rest of the program ...
7903. Production cycle 39.35 KB
The working period consists of the time for performing technological and non-technological operations; the latter include all control and transport operations from the moment the first production operation is completed until the delivery of the finished product. With a sequential type of movement, a production order - one part or one assembled machine or a batch of parts 1 series of machines 2 - in the process of their production switches to each subsequent operation of the process only after finishing the assembly processing of all machine parts of this batch ...
7548. EIS life cycle 34.12 KB
Life cycle EIS The need to create an EIS can be determined either by the need for automation or modernization of existing information processes or the need for a radical reorganization in the activities of the enterprise for conducting business reengineering. The needs for creating an EIS indicate, first, to achieve which goals it is necessary to develop a system; secondly, at what point in time it is advisable to carry out the development; third, what costs are necessary for the design of the system. EIS design ...
7492. PROJECT CYCLE 5.37 MB
The life cycle of a project is the starting point for investigating the problems of financing project work and making appropriate decisions. Each project, regardless of the complexity and amount of work required for its implementation, goes through certain states in its development: from the state when the project is not yet present to the state when the project is no longer there. For business people, the beginning of a project is associated with the beginning of its implementation and the beginning of investment Money in its execution.
8075. Second computation cycle 9.25 KB
In the second case, we got the so-called equivalent d-cubes for element 8, which differ from the first only by the inverse of the symbol d, so we need to take an equivalent d-cube AND get a solution.
21755. Project life cycle 154.99 KB
The effectiveness and sustainability of the activities of a modern organization is largely determined by the quality of the management activities carried out in the field of managing the project cycle. Competent management of the project cycle is an indicator of the correct direction of strategic development in accordance with the available opportunities.
2742. Loop with REPEAT postcondition 12.49 KB
You already know how to organize a cycle using while statement... Recall that when this statement is executed, the computer checks the value of the condition. If the condition is true, then the execution part of the while statement will be repeated until
20265. Life cycle of the company "FERRERO" 13.74 KB
Ale zupinila I have a good vibe on all the big men of the Ferrero confectionery company. The share of the skin fourth bitterness in the light - find yourself in the mouth of the lasuni, which is so good for yourself with the caress of the Italian group Ferrero, that at the moment of falling asleep in the coming start to get 70 rockies. -pine paste called Nutell ...
1002. Condition check, loop with additional condition 2.25 MB
Assembly language is a notation system used to represent, in human readable form, programs written in machine code. Assembly language allows the programmer to use alphabetic mnemonic opcodes
2341. Product life cycle and consumer behavior 14.84 KB
The life cycle of a product and consumer behavior of the LCI consists of several stages: research and development; implementation; increase in sales; maturity; recession. The first stage of the life cycle is research and product development. For an enterprise, this stage of creating a product is only costs and possible future income. The procedure for bringing a product to market takes time; during this period, sales increase slowly, which can be explained by such circumstances: delays in the expansion of production capacities; technical problems; ...

Please suspend AdBlock work on that website.

Sometimes you can't predict in advance how many times a loop should run. But at the same time, a certain condition is known when the cycle should stop. For example:

Program: Dice.

The program replaces the usual dice.

Control:

  • 1 - roll the dice;
  • 0 - Finish 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 the problem. It is clear that it is impossible to know in advance when the game will end. This means that you cannot use the for loop directly. One way out of this situation is to use other cyclic constructs. For example, a while loop.

Loop with while precondition

Listing 2.

While (condition) statement;

  1. The program encounters the keyword while, which means that a looping construction follows;
  2. The condition is checked. The logical expression in parentheses is evaluated;
  3. If the value of the condition is TRUE, then the body of the loop is executed. We pass to point 2;
  4. If the value of the condition is FALSE, then the cycle ends. Control is transferred to the operator following the loop body.

An operator means one 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 in words the algorithm of this program:

  1. We display the user menu and offer to enter a command;
  2. Launch while loop... We check the condition;
  3. If the user entered 0, then the loop execution condition becomes FALSE. The body of the loop is not executed. Control is transferred to the operator following the cycle. The string Good bye! ... The program ends;
    1. Selection operator:
      1. If the user entered 1, then we generate random number from 1 to 6 and display it on the screen. Exit the selection operator;
      2. If the user entered something else, we display an error message. Exit the selection operator.
    2. We display the offer to the user to enter a new command;
    3. We read the command code into the variable control;
    4. We return to checking the condition. Point 3.

The while loop is called a precondition loop 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 the while loop is the YET loop. Literal translation from English. This name reflects the very essence of the cycle.

Mnemonic rule:

WHILE the condition is TRUE, execute the loop body.

Loop with postcondition do-while

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

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

The syntax for this looping construct is as follows:

Listing 4.

Do operator; while (condition);

This construction works as follows:

  1. The program meets the do keyword. It means a do-while loop in front of it;
  2. The body of the loop 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 structure is terminated. The program is 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 did not work correctly. An error message was displayed when entering zero. In the previous program (with the while loop) such a situation could not exist, since equality to zero was checked in the loop condition. If you enter zero, the condition would become false, which means that the cycle would end and the body of the cycle would not be executed.

As we already said, in Pascal there are 3 ways to organize a loop (like):

2) Loop with postcondition

3) Loop with precondition

Loop In this article, we will consider the second type of loop - a loop with a precondition (WHILE loop)... If we use a loop with a counter when it is necessary to organize a loop with a known number of repetitions, then a loop with a precondition is used when the number of repetitions is unknown.

WHILE condition DO action; // body of the cycle

The body of the loop is executed as long as the condition is TRUE.

If there are several actions in the body of the cycle, operator brackets are used begin ... end;

WHILE condition do begin action_1; action_2; action_3; ... end;

Let's consider an example similar to the one discussed in the topic "Loop with a counter", but we will implement it using a loop WHILE.

It is required to display on the screen:

Hey
Hey
Hey
Hey

For implementation this example using a loop with a precondition, we need a variable n:

WHILE n<4 do writeln("Привет");

This loop will execute the command writeln (‘Hello’) an infinite number of times. Why? Because the variable n does not change and will always be less than 4. Therefore, it is necessary to add code in the loop that changes the variable n. For example: n: = n + 1.

WHILE n<4 do begin writeln("Привет"); n:=n+1; end;

Now the variable n will change with each execution of the loop body commands (with each iteration).

You need to remember: so that there is no looping in the loop WHILE- it is necessary to make sure that the variable from the condition changes in the body of the loop. This will not happen in a loop with a counter (looping), since we indicate the exact number of iterations.

Consider several problems where the number of repetitions in a loop is not clearly known.

The solution to this problem is based on the use of the WHILE loop, because we do not know when zero will be entered and we will stop entering numbers.

var a, s: integer; begin s: = 0; writeln ("Enter a number"); readln (a); while (a<>0) do begin s: = s + a; // calculate the sum S writeln ("Enter a number"); readln (a); end; writeln (s); end.

Why do we use the input of the number a (readln (a);) twice? The first time we enter the number a in order to enter the loop with some value of the variable a, which will be used in the condition of the WHILE loop. The second time the readln (a) command is used inside the loop - we enter numbers until we enter zero.

Objective 2.

You are given two segments A and B (A> B). Without using the operations of multiplication and division, determine how many segments B will fit in segment A.

Consider an image:

Those. from the figure you can see that we need to add the lengths of the segment A until the sum is greater than the length of the segment V... A loop with a precondition will help us with this - a loop while.

var a, b, s, k: integer; begin writeln ("Enter the length of the segment A"); readln (a); writeln ("Enter the length of segment B"); readln (b); k: = 0; S: = a; while s k: = k + 1; // variable k counts the number of times the loop body has been executed s: = s + a; // sums up the length of segment A end; writeln ("The segment B contains", k, "segments A"); end.

Let's consider the work of the program using an example: A = 5, B = 21 ... Let's write down the reasoning in the table:

Objective 3.

Using Euclid's algorithm, find the GCD of two numbers.

Consider a block diagram of Euclid's algorithm:

Let's write this algorithm using Pascal, based on this block diagram. As you can see, we have a cycle with a precondition (M> N)... There is one more condition inside the loop (M> N), i.e. operator IF… THEN.

var M, N: integer; begin writeln ("Enter M and N"); readln (M, N); while M<>N do begin if M> N then M: = M-N else N: = N-M end; write ("Н0Д =", М) end.

Similarly to Problem 2, one can check this algorithm by writing down the reasoning in the table.

Tags: C loops. C loops. Loop with postcondition. Loop with precondition. Loop with stripper. while. do while. for. break. continue

Introduction. Loops with a precondition.

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

Any cycle consists of a body and checking the condition under which this cycle should be terminated. The body of the loop is the set of instructions to be repeated. Each repetition 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 specified after keyword while. The body of the loop is two lines, one displays the number, the second changes it. Obviously this loop will run 10 times and print
0
1
2
3
and so on until 9.

It is very important that the condition for exiting the loop is ever fulfilled, otherwise an endless 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 determine the stop condition, so the loop does 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 a wrong action, it will be executed much more than 10 times. Since C does not monitor the overflow of a variable, it will be necessary 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. Different contents of the i variable will change the behavior.

If the body of the while loop contains one 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. Absence curly braces, especially at the beginning of training, can lead to errors. In addition, the code reads worse, and the extra parentheses do not greatly inflate the listings.

Loops with 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 (in contrast to 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. Suppose we need to integrate the function.

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

The integral is the sum of the infinitesimal. We can think of the integral as a sum, and we can simply replace the infinitesimal values ​​with small values.

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

From the formula, you can see that we actually split 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. Adding the areas of all rectangles, we thereby obtain the value of the integral with some error.

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

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

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 every time we find the value of the function at the left point. Therefore, this method of numerical integration is called the left rectangle method. Similarly, you can take the right value. Then it will be the method of right rectangles.

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

The amount in this case will be equal to 0.338. The left and right rectangle method is not very accurate. We actually approximated (approximated) 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 =" (! LANG: Numerical integration of a function by
trapezium"> Рис. 4 Численное интегрирование функции методом!}
trapezium

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

Let's go back to our rams. Let's 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 follow these examples, you will see that the loops are executed from two to four times. It is worth paying attention to this, because incorrectly changing the loop counter often leads to errors.

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

Let's solve a simple problem. The user enters numbers until the number 0 is entered, then displays the largest one entered. There is a catch here. How many numbers the user will enter is not known. Therefore, we will create an infinite loop, and we will exit from 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"); / * endless loop * / while (1) (printf ("Please, enter number:"); scanf ("% d", & num); / * condition to exit the loop * / 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 compare it with the current maximum.

Infinite loops are used quite often, since the input data are not always known in advance, or they may change during the program's execution.

When we need to skip the body of the loop, but at the same time continue the execution of the loop, we use the operator continue... A simple example: the user enters ten numbers. Find the sum of all the positive numbers that 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's another example. It is necessary for the user to 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 is

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

For example, let's display 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 print numbers from 5.3 to 0.1. The for loop may not have some "blocks" of code, for example, it may be missing initialization, checking (then the loop becomes infinite) or changing the counter. Here is an example with an integral 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 take a 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 some of the actions

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

NOTE: While this can be done, please do not! This reduces the readability of the code and leads to subtle errors.

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

F x ′ = d x d y

Take a point on the curve with coordinates (x; f (x)), move one step h forward, 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) = tan α

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

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

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. To solve, we need, as in the problem with an integral, variables for the boundaries of the search area a and b, present value x and step h... In addition, a maximum value is required maxVal and coordinate maxX this maximum value. For 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 over the entire region 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 gives max value = 1.391 at 1.077

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

Nested loops

Consider an example where loops are nested within each other. Let's display 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); } // После чего переходим на новую строку printf("\n"); } getch(); }

In this example, in the first loop over the variable i nested second loop on variable j... The sequence of actions is as follows: first we enter the loop by i, then for the current i Numbers are output 10 times in a row. After that, you need to go to a new line. Now let's only display the items below 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 from the current cycle. This example can be rewritten as follows

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 cycle 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 mailbox