Cycles and other controls. Structural programming. Control structures in Visual Basic

Managing operators (Control Statement) are called executable operators changing the sequence of executing the instructions of the program. From all operators used in programming languages, control operators caused the most disputes. The main subject of discussion is the easiest GOTO control operator. It allows you to change the procedure for executing the program and go to the execution of the program, starting with a certain place, which is indicated by the name or number. Consequently, this operator is nothing more than the direct application of the machine transition command. Availability of such an operator in the language high level Allows programmers to write such unsystematic programs1:

goto 40 20 Apply Evade Procedure

goto 70 40 IF (KryptoniteLevel< LethalDose) then goto 60

60 Apply the RESCUEDAMSEL 70 procedure ...

whereas all these actions can be written with the help of one structure:

if (kryptonitevel.< LethalDose)

tHEN (Apply the RESCUEDAMSEL procedure) ELSE (Apply the Evade procedure)

In order to avoid such difficulties, modern programming languages \u200b\u200bcontain such control operators that allow you to record branching structures using one expression. Some generally accepted branching structures and their corresponding programming operators are depicted in different programming languages. 5.7. Please note that we have already met with the first two structures in chapter 4. In our pseudocode, they are represented by IF-THEN-ELSE and WHILE operators. The third structure, which is called the choice, can be considered as an expansion of the structure I F-THEN-EL SE. The difference between them is that the IF-THEN-ELSE operator allows you to choose from two options, and the CASE operator is from several.

Another common structure is the operator cycle for (Fig. 5.8), similar to the WHILE operator of our pseudocode. The difference between them is that initialization, modification and verification of the cycle completion conditions are combined in one operator. Such an operator is convenient to use when the cycle body needs to perform a certain number of times - once for each value of the parameter variable at a specified interval. In particular, the operator shown in Fig. 5.8, prescribes the cycle body to be made several times: when the value of the COUNT variable is 1, then when its value is 2 and the last time it is equal to 3.

From the above examples, it can be concluded that the branching structures with minor variations are present in imperative, and in object-oriented programming languages. In theoretical computing technology There is an assumption that the solution of any task having an algorithmic solution can be written using a limited number of structures. We will discuss this statement in chapter 11. In the meantime, it should be noted that the study of the programming language is not an infinite study of various management operators. In fact, most control structures used in modern programming languages \u200b\u200bare a kind of structures described in this chapter.


The choice of what structures include in programming language, taste. Before the creator of the tongue, the goal is to develop a language that not only allows you to record algorithms in a convenient form for reading, but also helps the programmer in this. This goal is achieved by limiting the use of those elements that have historically led to inaccient programming, and the introduction of well-thought-out elements. As a result, we have structural programming (Structured Programming), which combines programs for writing programs and proper use Management operators. The goal is to create a program, easy for understanding and performing tasks set before it.

Comments

Experience shows that when a person is trying to understand the program big size, it is not so important how well the programming language is thought out and how its properties are used, how useful or even mandatory additional Informationpresented in a normal human language. Therefore, in programming languages, it is possible to accommodate in the program explanatory comments (Comments). The translator ignores comments, so their presence or absence does not affect the program from the point of view of the machine. The program version of the machine language generated by the translator remains unchanged, with or without comments. But the information they contain is important to humans. Without it, it would be impossible to understand large and complex programs.

Visual Basic is an object-oriented programming language. It was developed by Microsoft as a tool with which users operating system Microsoft Windows. Could develop your own graphic user interface. In fact, Visual Basic is more than just a programming language. It is a complete package for developing softwarewhich allows the programmer to create a user interface from certain components (such as buttons, checkboxes, text fields, scroll bars, etc.) and redo these components according to their needs, describing how they should respond to certain events. For example, in the case of the programmer button, it can describe what should happen if you click on the mouse. This method of creating software from predetermined components is a modern tendency in software development.

Due to the popularity of the operating room windows systems And the convenience of using the Visual Basic package, Visual Basic has been today one of the most common programming languages. On the other hand, due to the fact that Visual Basic is compatible with software Microsoft, it is not recognized as a general purpose programming language.

There are two main ways to separate comments from the text of the program. One of them is to conclude a comment in special brackets. Another way is to designate the beginning of the comment that can occupy the remaining part of the line to the right of the sign. In C ++, with # and Java, both ways to write comments are possible. In them, the comment can be placed between the signs / * and * / or start it with //. Thus, in C ++, with # and Java, both records are allowed:

/ * This is a comment. * /

// This is a comment.

A few words should be said about what to write in the comments. Novice programmers when they are talking about the need to supply a program with comments, usually to such an expression, as

Approachangle - Slipangle - Hyperspacelncine:

add a comment "Subtract HyperspacelnCine from Slipangle and assign the value of the Approachangle variable." Such comments do not make a program more understandable, but only lengthen it. Remember that the purpose of the comment is to explain the program, and not repeat it. IN this example It is better to explain why the value of the ApproachanGl E variable is calculated (if it is not clear from the program). For example, a comment: "Approachangle variable is used later to calculate the value of the Forcefiel Djetti Sonvel Ocity variable," much more useful than the previous one.

In addition, comments placed between program operators sometimes make it difficult to read and understand the program. It is best to put comments regarding one program block in one place, for example, in its start. This is how some plot of the program is created, which contains a description of the purpose and general characteristics Program block where the user can find the necessary explanations. If you use such a reception for all program blocks, then the program acquires uniformity: each block consists of explanatory comments followed by a formal representation of this block. Such uniformity greatly facilitates the program reading.

Procedural units

In previous chapters, we talked about the benefits of splitting large programs for small managed units. In this section, we will focus our attention on the concept of a procedure, which is the main means of obtaining a modular presentation of the program written in the imperative programming language. The procedure is also a tool that is used in the program written in an object-oriented language to describe how the object must respond to various input signals.

Procedures

Procedure is a set of commands for performing some task that other software units can use as an abstract tool. The control is transmitted to the procedure (using the machine language transition command) when its actions are necessary, and then, after completing the procedure, returns again returns the original software unit (Fig. 5.9). The process of transmitting the procedure is called the procedure call. The program unit that requests the execution of the procedure, we will be called the calling program or calling module (Calling Unit).

In many ways, the procedure is a small program consisting of description operators followed by executable operators that determine the action procedure performed. As a rule, the variable declared in the procedure is a local variable (Local Variable), that is, it can only be used in this procedure. This approach eliminates the confusion that may occur if two independent pro-fools use variables with the same names. Variables whose action is not limited to any one part of the program are called global variables (Global Variable), they are available anywhere in the program. Most programming languages \u200b\u200buse local, and global variables.

In the programming languages \u200b\u200bunder consideration, the description of the procedure is almost the same as in our pseudocode (see chapter 4). It begins with an expression, which is called the heading of the procedure and which, among other things, contains the name of the procedure. The heading is followed by operators defining the procedure in more detail.

However, in contrast to our non-strict pseudocode, in which we requested the procedure using such an expression, how to "apply the Deacti Vatecrypton procedure", most modern programming languages \u200b\u200ballow you to call the procedure simply by specifying its name. For example, if getnames, SortNames and Writenames are procedure names for obtaining, sorting and output to print a list of names, a program that receives a list, sorting it and printing, can be written as

Apply GetNames Procedure. Apply the SortNames procedure. Apply the Writenames procedure.

Note that since we have assigned the name that means the action performed by this procedure, this brief form of recording is a command sequence reflecting the program assignment.

The simplest structure is followed. It can be represented as:

Modules "A" and "B" may contain both one operator and any number of structures following each other, incl. and discussed below.

The structure of the fork (if - otherwise) serves to select one of two possible paths performing the algorithm. It is the basis of the inspection. Looks like a fork so:

The structures in each other are embedded in each other, for example, thus.

The number of embedded structures invested in each other is limited by the PC capabilities and assigned to it. This amount is usually negotiated in the language description. To ensure the readability of the flowchart, you can re-replace the embedded structures, and the block diagram of each rectangle is displayed in detail on a separate sheet. In general, any block diagram or program is better read, if the entire page is posted on one page.

The structure presented on the last block diagram allows you to select one of three ways. Similarly, with the help of nested structures, you can organize a choice of one of any number of paths. Since the need for this appears quite often, a special structure has been introduced - a choice that looks like in the following way

Here, the symbol "P" is still designated by the condition, based on the execution of which one of the possible paths are made.

When developing algorithms, it is often extremely important to repeat any operation or a group of operations. For the image of such fragments of the algorithm, special structures are provided - cycles. ʜᴎʜᴎ There are three types: cycle-so far, cycle-to and cycle with a meter. The operation of the cycle is still depicted by the next block diagram.

Before the first execution of the block of operators, which is customized by the body of the cycle, is checked by the "P" condition and, in case it is true, the cycle body is performed, and the control returns to the beginning of the cycle. Next, the condition is checked again, and so until the cycle condition becomes false. In this case, the execution of the cycle is terminated. It is performed until the condition is performed.

Cycle-to is organized in a way.

The truth verification of the cycle condition is made after the body's body is performed, and the output from it is carried out with the truth of the condition. Τᴀᴋᴎᴍ ᴏϭᴩᴀᴈᴏᴍ, the cycle body is performed at all once unlike cyclewhich, if the cycle condition is not fulfilled, is not fulfilled.

The third type of cycle is a cycle with a meter. It is applied in cases where to repeat the cycle body is extremely important in the number of times. Its structure can be depicted by the following block diagram.

It shows that this cycle is a special case. cycleBut since this case is common, then in programming languages, in particular, in VBA, to describe the cycle with a meter introduced special operator.
Posted on Ref.rf
For this reason, we allocated a special structure for this cycle.

As an example, consider the block diagram of finding the maximum element in the table from N numbers.

Here max - the maximum number, I is the number number in the number X, N - the size of the table. The block diagram contains the following structural structures: follow, cycle-while, which is performed until the number of the number of the number is less or equal to the size of the table, and the fork in which the path containing the assignment of the current number is selected from the MAX Table, in the event In the event that this variable is less than the current number.

The main management structures are concepts and types. Classification and features of the category "Basic Control Structures" 2017, 2018.

Cycle operators Cycle operators are used to organize repeatedly repetitive calculations. To organize a cycle, a variable is called a cycle parameter or a cycle control variable. Any cycle consists of: initial installations or a cycle parameter initialization unit; Cycle body, that is, those operators that are performed several times; block modification of the cycle parameter; Checking the exit conditions from a cycle which can be placed either to the cycle body then talk about a cycle with a precondition or after the body ...


Share work on social networks

If this job does not come up at the bottom of the page there is a list of similar works. You can also use the Search button.


Topic 2 Managers Operators

2.1 Basic structures structural programming

IN programming theoriesit has been proven that the program for solving the problem of any complexity can be made only of three structures calledconnection, branching and cycle. They are called basic structuresstructural programming.

Connection a design is called a sequential execution of two or more operators (simple or composite).

Branch sets the execution either one or another operator depending on the implementation of any condition.

Cycle specifies the multiple execution of the operator.

A feature of the basic designs is that any of them has only one input and one output, so the designs can be invested in each other in an arbitrary manner.

Figure 2.1 - Basic structural programming designs

The purpose of using basic structures is to obtain a simple structure program. This program is easy to read, debug and, if necessary, make changes to it.

Any expression that ended with a semicolon is considered as an operator, the execution of which is to calculate the expression.

2.2 Relations and logical operations

Operations of the relationship(<, <=, >,\u003e \u003d, \u003d\u003d,! \u003d) compare the firstoperand with the second. Operands. there may be an arithmetic type or pointers. The result of the operation is the valuetrue or False . Operations of comparison on equality and inequality have a smaller priority than other comparison operations. For example:x\u003e \u003d 0, y! \u003d 10, z \u003d\u003d 0.

ATTENTION! Pay attention to the difference between the validity check operation (== ), which is the result of which istrue or False , and the assignment operation (= ), the result of which is the value assigned to the left operand.

Logical operations(&&, ||, ^). Operands. logical operations and (&&), or (|| ), Excluding or (^ ) must have a type allowing transformation to typebOOL, with the operands in one operation can be different types. The result of the operation istrue or False.

Operation resultlogical and matters true only if both operands mattertrue. . Operation resultlogical or matters true if at least one of the operands matterstrue. . Operation resultlogical excluding ormasits True. if one of the operands matterstrue, and the second is false. Logical denial ( !) As a result, the valuefalse if the operand is true, and True value if the operand is false. Operand it may be an arithmetic type. In this case, executedimplicit conversiontype BOOL . Logical operations are performed from left to right. If the first operand values \u200b\u200bare sufficient to determine the result of the operation, the secondoperand is not calculated.

Table of operations and, or, excluding or, not

(A and B - Operands)

A && B.

A || B.

A ^ B.

Examples of expressions S. logical operations:

x\u003e 0 && Y<=10

(A.< -1 && b > 0) || C! \u003d 100

Conditional operation(? :). This only B.C ++ Ternar operation (has three operands), its format:

operand_1? Operand_2: Operand_3.

Operands. calculate from left to right. The result of calculating the first operand must be type that can be converted to typebOOL . If the result is equaltrue. The result of the fulfillment of the entire conditional operation will be the value of the second operand, otherwise the third operand. Their types may be different.

Example: Let it require that some whole value increase by 1 if its value does not exceedn. , otherwise it took a value 1. It can be written using one code line:

i \u003d (i< n) ? i + 1: 1;


2.3 Branch operators. Conditional operator if.

Conditional operator if.used to branch the process of computing into two directions.Algorithm scheme the operator is shown in Figure 2.1. Operator format:

if (expression) operator_1; [ELSE Operator_2;]

First, the expression is calculated, which can have an arithmetic type or type of pointer. If it is not zero, i.e. equallytrue. , then the first operator is performed, otherwise - the second. After that, the control is transmitted to the operator following the conditional. One of the branches may be absent.

If some branches are required to perform several operators, they must be concluded in the block. The unit may contain any operators, including descriptions and other conditional operators.

Examples:

iF (A.< 0) b = 1;

iF (A.< b && (a >d || a \u003d\u003d 0))

B ++;

eLSE.

(b * \u003d a; a \u003d 0;)

iF (A.< b)

iF (A.< c )

M \u003d a;

eLSE.

M \u003d c;

eLSE.

IF (B.< c )

M \u003d b;

eLSE.

m \u003d c;

In Example 1. no brancheLSE. . This design is called "Operator Skip", sinceassignment either it is performed or is passed depending on the implementation of the condition.

If you need to check several conditions, they are combined by signslogic operations. For example, expressionin Example 2. will be truly in the event that condition is performed simultaneously< b и одно из условий в скобках. Если опустить внутренние скобки, будет выполнено сначала логическое И, а потом – ИЛИ.

Operator in example 3 calculates the smallest value of three variables.

Operator syntaxif. There should be no more than one operator in its branches. If they are more, then they must be combined into the block withcurly brackets or using operations "comma" (,).

Example. A shot shot on the target shown on Figure 3.2. Determine the number of points.

Figure 3.2 - Target

#Include.

iNT MAIN ()

float X, Y;

int kol;

PrintF ("\\ n Enter the shots coordinates ");

Scanf ("% f", & x);

Scanf ("% f", & y);

If (x * x + y * y< 1)

Kol \u003d 2;

ELSE.

If (x * x + y * y< 4)

kol \u003d 1;

eLSE.

kol \u003d 0;

printF ("\\ N points:% d", KOL);

2.4 Branch operators. Multiple selection operatorswitch

SWITCH operator (switch)designed to branch the calculation process into several directions. Operator format:

switch (expression)

Case Constant) Emploitation_1: Operators1;

Case Constant) Emploitation_2: Operators 2;

...

Case Constant_Nespective_n: Operators N;

The execution of the operator begins withcalculations of expression(it should be integer ) and then control is transmittedcase mark - operators marked with a constant expression, the value of which coincided with the calculated, after which all other branches are successively executed if the output fromthe switch is clearly not specified.

All constant expressions should have different meanings, but be the sameinteger type. Several marks can follow in a row. If the coincidences did not happen, operators are performed after the worddefault. (and in its absence, control is transmitted to the followingswitch operator).

If in some ofcase -Mets no operatorbreak then operators are also running in the followingcase -Mike and so on as long as the operator does not meet somewherebreak.

Example (the program implements the simplest calculator for 4 actions):

#Include.

iNT MAIN ()

iNT A, B, RES;

char Op;

printf ("\\ n Enter the 1st Operand: ");

scanf ("% d", & a);

printf ("\\ n Enter the operation sign: ");

scanf ("% C", & OP);

printf ("\\ n Enter the 2nd Operand: ");

scanf ("% d", & b);

bOOL F \u003d TRUE;

Switch (OP)

Case "+": res \u003d a + b; Break;

Case "-": res \u003d a - b; Break;

Case "*": res \u003d a * b; Break;

Case "/": res \u003d A / B; Break;

default: Printf. ("\\ n Unknown Operation"); F \u003d false;

iF (F)

printf ("\\ N Result:% d", Res);

Exit Switch usually running using operatorsbreak or Return.

2.5 Cycle operators

Cycle operators used to organize multiple repetitive calculations.

For the organization of the cycle, a variable is necessary, calledcycle parameter or cycla control variable. Any cycle consists of:

  • initial installations or cycle Parameter Initialization Block;
  • body cycles , that is, those operators that are performed several times;
  • block modification of the cycle parameter;
  • check output conditions from the cycle that can be posted eitherbody cycles (then they talk about the cyclewith precondition), or after the cycle body (cycle with postcondition).

Figure 3.3 - Two types of cycles

One cycle pass is callediteration . Integer cycle parameters varying for an integer on eachiterations are called cycle meters.

You can not transfer control from outside the cycle. The output from the cycle is possible both when performing the exit condition and operators.break, Return or unconditional transitiongoto.

2.6 Cycle with Prelation (While)

Cycle with preconditionimplements the algorithm scheme

while (expression) operator;

For example:

The expression defines the repetition conditionbody cycles represented by a simple or composite operator. If the expression is not 0 (true), the cycle operator is performed, after which the expression is calculated again. If, with the first check, the expression is 0 (false), the cycle will not be completed. The type of expression should be arithmetic or shown to it.

function valuesy \u003d x 2 +1 in the introduced range):

#Include.

iNT MAIN ()

float XN, XK, DX;

float X \u003d xn; // Initial Settings Cycle

While (X.<= Xk) //проверка условия выхода

Printf ("\\ N% 5.2F% 5.2F", x, x * x + 1); //body

X + \u003d dx; //modification

2.7 Cycle with postcondition (Do While)

Cycle with postbandimplements the algorithm scheme shown below and has the form:

doo operator While expression;

First, simple orcomposite operatorThe cycle body is, and then the expression is calculated. If it is not equal to 0 (true), the cycle body is performed again, and so on until the expression becomes zero (false) or in the cycle body will not be performed anycontrol operator. The type of expression should be arithmetic or shown to it.

Example (program checks input):

#Include.

iNT MAIN ()

char Answer;

printf ("\\ n Buy an elephant!");

scanf ("% C", & Answer);

while (Answer! \u003d "Y");

2.8 Cycle For

Cycle for implements the scheme of the algorithm below and has the form:

for (initialization unit; Conditions check unit; modification unit)

Cycle body;

Example:

Initialization unitused to declare and assign initial values \u200b\u200bof the values \u200b\u200bused in the cycle. In this part, you can write several operators separated by the comma.

Conditions check blockdetermines the condition of the cycle: if it is not equal to 0 (truly), the cycle is performed.

Modification unitperformed after eachiteration cycle and used usually to change the cycle parameters. In terms of modifications, you can write several operators through the comma.

Simple or composituoperator representscycle body . Any of the parts of the operatorfor it can be omitted (but a point with a comma should be left in their places!). In any part, you can use the "comma" operation (sequential calculation), for example:

for (int i \u003d 1, s \u003d 0; i<= 100; i++)

S + \u003d i; // Amount number from 1 to 100

Example (program prints tablefunction valuesy \u003d x 2 +1 in the entered range):

#Include.

iNT MAIN ()

float XN, XK, DX;

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

scanf ("% f% f% f", & xn, & xk, & dx);

For (Float x \u003d xn; x<= Xk; X += Dx)

Printf ("\\ N% 5.2F% 5.2F", x, x * x + 1);

2.9 Nested cycles

Each of the cycle operators can be invested in any other in an arbitrary sequence. The depth of the cycles is not limited. It is determined only by the algorithm of the problem being solved.

Below is an example of nested cycles.for

This program fragment works as follows. For one value of the external cycle parameteri (for example, i \u003d 1 ) Internal cycle parameterj. varies in the range from the minimum to the maximum value (from 1 toM. ). Only after that the parameteri. Increases per unit. Thus, the cycle body will be executedN * M times.

Other options for nested cycles work in the same way: the external cycle parameter varies slowly, and the internal quickly. They are recommended to master their own. For this, the diagram of the internal cycle algorithm must be inserted entirely instead of the body of the cycle.

2.10 Control Transmission Operators

In C ++. there are five operators changing the natural procedure for performing computing:

  • output operator from the cycle andswitch Break;
  • transition operatorto the next iteration of the CONTINUE cycle;
  • refund operator functionreturn;
  • operator unconditional transitiongoto;
  • exception generator operatorthrow.

Output operator Break. used for immediate completioncycle Operator or Switch . The execution is transmitted to the next after the completed operator.

Consider its use on the exampleopen iterative cyclefor . On the example of calculating the amount of numbers from 1 to 100.

int i \u003d 1, sum \u003d 0;

for (;)

If (I\u003e 100) Break;

sUM + \u003d I;

i ++;

Transition to the next iterationcycle Continue. misses all operators remaining to the endbody cycles and transfers control to the modification of the cycle parameters (in the case of a cyclefor ) and the beginning of the nextiteration.

Consider it using an example of calculating amount 1 /x, if x varies in the range [-5, 5].

#Include.

iNT MAIN ()

float X, SUM \u003d 0;

for (x \u003d -5; x<= 5; X++)

If (x \u003d\u003d 0)

Continue;

Sum \u003d Sum + 1 / x;

PrintF ("\\ N sum \u003d% f", SUM);

Refund operator functionreturn. completes the execution of the function and transfers control to the point of its call. We will look at it together with the functions in the appropriate topic.

Unconditional transition operatorgoto has a format:

goto label;

In the body of the same function there must be exactly one design of the form:

tag: operator;

Goto operator transfers control to a marked operator.Label - this is an ordinary identifier,property area Which is a function, in the body of which it is found.

Using the operator of unconditional transitionjustified in two cases:

  • forced output down the text of the program from severalnested cyclesor switches;
  • the transition from several features of the function to one (for example, if you need to always perform any actions before going out of the function).

In other cases, to record any algorithm there are more appropriate means.

Exceptional situation(or just an exception ) generates either a programmer using the operatorthrow or the fulfillment itself. This happens when any errors occur during the program, for example, dividing to zero oroverflow. Mechanism except handlingimplemented byC ++. Allows you to respond to such errors and thus avoid the emergency completion of the program. It will be considered in another topic.

Other similar works that may interest you. Ishm\u003e

2784. Conditions and choice operators 16 kb.
Operator Condition IF. Therefore, you can already write down the following assignment operators: Koren: \u003d SQRTXY; Modul: \u003d BSXY. To implement such conditional transitions in the Pascal language, IF and ELSE operators are used as well as the unconditional transition operator. Consider the IF operator.
2750. Write and Writeln operators 12.34 Kb.
Write English The Writeln operator performs the same action but since he has another end of LN LINE eng. General view: WRITE Writeln expressions list Write and Writeln procedure expressions are used not only to display the result but also to output various messages or queries.
6706. Structured Queries Language - SQL: History, Standards, Basic Language Operators 12.1 Kb.
The structured language of SQL queries is based on a relational calculus with variable covers. SQL Language is designed to perform operations on the tables Creating Delete Structure Changing and On Table Data Selection Change Adding and Deleting as well as Some Related Operations. SQL is an indispensable language and does not contain control operators organization of subroutines for incorporation and t.

^ Programming conditional transition operators IF-ELSE Programming the SWITCH I selection operators »- Programming the WHILE, DO-WHILE cycle operators and for assembler language - Machine command language. It supports only basic mechanisms of program organization. It does not have control structures, natural for high-level languages. We are talking about the support of the designs of the type of selection operators, the organization of cycles, etc. In the last chapter, we initiated the discussion of these issues, considering the principles of organizing cycles in the assembler programs. The purpose of this chapter is to develop templates of control structures on an assembler similar to the standard operators of the high level language. We will simply, we will simply open any textbook on the language C or C ++, we will make the list of control operators given in it and show the ways to implement them on the assembler. The standard list will be as follows: select operators :? Conditional operator IF-ELSE; ? Switch switch; Ш Cycle operators: p cycle with WHILE; PO CYCLE WITH DO-WHILE; N Iteration cycle for; ^ CONTINUE AND BREAK operators.

More on the topic Chapter 11 Programming Model Control Structures:

  1. Chapter 2 Negative and Positive Programming

In the simplest program, operators are performed sequentially, i.e. Exactly once and in the order as they meet in the text of the program. However, in real programs, operators can be repeated or executed only under a certain condition. Managing operators are used to create nonlinear structure programs.

The control operators include the following operators:

    Branch operators:

    the conditional operator is if ELSE - implements algorithmic alternative and selection structures (see Appendix 1);

    selection operator - Switch - partially implements the algorithmic structure of the choice (see Appendix 1);

    Cycle operators:

      • a cycle with a precondition - WHILE - implements the algorithmic structure of the cycle with the precondition (see Appendix 1);

        the cycle with the post-DO WHILE - realizes the algorithmic structure of the cycle with the postlane (see Appendix 1);

        a cycle with parameter - FOR - implements the algorithmic structure of the parametric cycle (see Appendix 1).

Conditional operator (if.eLSE.)

The conditional IF statement is used to branch the calculation process into two directions, respectively, it implements the algorithmic structure of the alternative, the block diagram of which is as follows:

If a<Условие> True, then running<Оператор 1>otherwise executed<Оператор 2>.

An example of using a conditional operator to branch the calculation process into two directions:

// calculating the module y \u003d | x |

iF (X.< 0) { y= -x; }

The IF operator is also used to implement the algorithmic selection structure (see the block diagram below) when the SWITCH selection operator cannot be used.

Using the Called Operator for the implementation of the algorithmic structure:

An example of using a conditional operator to implement the algorithmic structure:

// Calculation Y \u003d SIGN (X) - a simpler way to implement

iF (X.< 0) { y= -1; }

if (x \u003d\u003d 0) (y \u003d 0;)

if (x\u003e 0) (y \u003d 1;)

// Calculation Y \u003d SIGN (X) - a more efficient way of implementation

iF (X.< 0) { y= -1; }

eLSE if (x \u003d\u003d 0) (y \u003d 0;)

eLSE if (x\u003e 0) (y \u003d 1;)

Choice operator (switch) + interrupt operator (break)

The SWITCH operator is designed to branch the calculation process into several directions. This operator implements the algorithmic structure of the choice. However, it has limited use, because It does not imply set arbitrary conditions. Conditions in the SWITCH operator have the following structure<Выражение> == <Константа>.

Operator format:

switch (<Выражение>)

case<Константа 1>:

<Оператор 1>

case<Константа 2>:

<Оператор 2>

case<Константа M>:

<Оператор M>

<Оператор M+1>

If a<Выражение> Takes the value equal<Константа 1>, then running<Оператор 1>; if a<Выражение> Takes the value equal<Константа 2>, then running<Оператор 2> etc. If a<Выражение> takes the value other than the indicated constants, then<Оператор M+1>.

An example of using the selection operator:

// user response analysis

scanf ("% C", & Answer);

printF ("\\ Novy pressed 1");

printf ("\\ Ns pressed 2");

Break operator interrupts the execution of the Switch operator. If it were not, then all operators inside the Switch would be performed consistently at each other. For example, so:

// user response analysis

scanf ("% C", & Answer);

printF ("\\ Novy pressed 1");

printf ("\\ Ns pressed 2");

printf ("\\ Ns pressed something wrong");

When entering a user of the '2' symbol, two messages will appear on the screen:

"You have pressed 2"

"You have pressed something wrong"

Cycle operator with precondition (while)

The operator is used to organize multiple repetitive calculations that may not be fulfilled. The WHILE operator implements the algorithmic structure of the cycle with the precondition, the block diagram of which is shown below. This algorithmic structure is used when in advance the number of iterations (repetitions) is not known, and maybe the absence of repetitions.

Operator format:

while (<Условие>)

<Оператор>

First checks<Условие>. If a<Условие> True, then running<Оператор> until<Условие> Will not be false. If a<Условие> It became false, the control is transmitted to the operator following the cycle.<Условие> - this is the condition of continuing the cycle,<Оператор> - This is the body of the cycle (repeated action + action to exit the cycle).

Comment.<Оператор> may not be fulfilled never if<Условие> Initially false.

An example of using the operator with the precondition:

char String \u003d "This is an example";

Count \u003d 0; // preparation

while (String! \u003d '\\ 0') // Continuation Condition

(Count ++;) // Cycle body (Repeated action +

In this example, the cycle will never be completed if the string string is empty.

Consider another example in which the WHILE statement is used, but more correctly use the DO WHILE statement:

// enter the Russian letter

char russianletter;

scanf ("% c", & russianletter); // preparation

while (russianletter< ‘A’) ||

(Russianletter\u003e 'I')) // Continuation Condition

(SCANF ("% C", & russianletter);) // Cycle body (repeated action + // action for exiting a cycle)

Cycle operator with postband (do.while)

The operator is used to organize multiple repetitive calculations that are performed at least once. The DO WHILE statement implements the algorithmic structure of the cycle with the post-block, the block diagram of which is shown below. This algorithmic structure is used when the number of iterations is not known in advance, but at least one iteration is always performed (for example, if data is being commissioned in the cycle).

Operator format:

<Оператор>

while (<Условие>);

First executed<Оператор>, then checked<Условие>. If a<Условие> True, then again is performed<Оператор>. It goes on as long as<Условие> Will not be false.

Comment.<Оператор> Always performed at least once.

An example of using a cycle with a postband:

// Require a number from 0 to 10

// Preparation is absent

(SCANF ("% D", & Number);) // Cycle body (Repeated action +

// action to exit the cycle)

while ((Number< 0)||(Number > 10)); // Term condition

The example uses the DO WHILE cycle, because The number is first introduced, and then checks it.

Please note that after the WHILE operator puts a point with a comma;.

Cycle operator with parameter (for)

The operator is used to organize multiple repetitive computing and is essentially similar to the WHILE cycle, but has a more compact entry. The FOR operator implements the algorithmic structure of the parametric cycle, the block diagram of which is shown below. This algorithmic structure is used when the number of iterations is known in advance.

Operator format:

for (<Оператор инициализации>; <Условие>; <Оператор модификации>)

<Оператор>

First executed<Оператор инициализации> And checks<Условие>. If a<Условие> True, then running<Оператор>. Then executed<Оператор модификации> And checks again<Условие>. If a<Условие> True, then running<Оператор> etc. The cycle is completed when<Условие> It becomes false.

Comment. Cycle for how and the While cycle may not be completed.

Example of using a cycle with a parameter:

y \u003d 1; // preparation

for (i \u003d 1; i<= n; i++) // оператор инициал.; условие; оператор модификации

(Y \u003d Y * i;) // Body Cycle (Repeated Action)

In this example, before the cycle is performed, it is known that the variable I must vary in the range from 1 to n.

And now we will consider how the same task is solved using the WHILE cycle:

// Calculation of factorial Y \u003d N!

y \u003d 1; // preparation

i \u003d 1; // Preparation (initialization operator)

while (I.<= n) // условие продолжения

y \u003d y * i; // Repeated action

i ++; // action to exit the cycle (modification operator)

This example shows that the use of the WHILE cycle complicates the program code, and therefore it is preferable to use the FOR cycle when the number of iterations performed is known in advance.