Menu
Is free
registration
home  /  Education/ Control structures in PHP. C language control constructs

Control constructs in PHP. C language control constructs

8. Structural programming.

Structured programming can be defined as programming focused on making programs easy to write and understand by humans, not computers. It pursues the following goals: to write programs of minimal complexity, to make the programmer think clearly, to facilitate the perception of the program. To achieve these goals, the structural program must meet the following basic requirements.

    The text of the program should be a composition of three basic structures: sequential connection (following), conditional clause (branching) and repetition (loop).

    The use of jump statements like GOTO should be avoided wherever possible (if restrictions on volume and execution time are not critical, then everywhere). The worst use of a GOTO is to jump to a statement higher (earlier) in the program text.

    If possible, avoid using the ELSE statement.It is usually unnecessary because it is equivalent to the IF (not<условие>) THEN. The ELSE construction is needed only in that rare situation when the THEN construction changes one of the variables in the condition.

    The program should be written in an acceptable style that makes it easy to understand and modify.

    Each module must have exactly one input and one output.

    The program is a simple and clear solution to the problem.

8.1 Control constructions of structured programs.

Structural programs are composed of three main building structures for computing process control:

    following- indicates the sequential execution of actions;

    branching- corresponds to the choice of one of two options of actions depending on the condition (value of the predicate);

    precondition loop- defines the repetition of actions until a given condition is violated, the fulfillment of which is checked before the beginning of each repetition.

In addition to the basic ones, three more control structures can be used, which are easily implemented on their basis:

    choice- denotes the choice of one option of actions from several, depending on the value of a certain value or condition;

    loop with postcondition- determines the repetition of actions until a certain condition is met, the check of which is carried out after each repetition;

    loop with a given number of repetitions (counting cycle) - determines the repetition of actions a specified number of times.

Actions that are components of structured programming constructs are either simple statements of the language used (for example, assignment, input, output, subroutine call statements), or program fragments that are a composition of basic control structures.

    Structured programming constructs

8.2. The concept of programming style and its characteristics.

Programming style is the manner in which a developer uses a programming language to write and format the text of a program. A good style is one that makes it easier for people to perceive and understand the program. A programming style is characterized by two main factors: the clarity of the program and the way in which the language is used.

Following the principle of program clarity is a fundamental prerequisite for good programming style and requires an emphasis on simplicity and clarity of the text when writing program code by ignoring less important criteria, for example, brevity or machine efficiency. To improve clarity when writing a program, you must adhere to the following basic rules.

    Each program object must have a meaningful, meaningful name that defines its purpose.

    Program objects should not have similar names, for example, differing only in case of characters or one or two characters. Also can not be used as names keywords language and similar to them in writing.

    Unnecessary intermediate variables should be avoided.

    To avoid ambiguity, parentheses should be used to explain the order in which operations are performed.

    You should not put multiple language statements on the same line.

    The text of the program must be written using line gaps and indents.

    The text of the program should be commented in all those places where it may be difficult to understand or the meaning of the given code is not obvious. Comments should contain information that explains the code and reflects the purpose of performing certain actions and the consequences to which they lead. In addition, it is recommended to use comments when declaring program objects.

    You should adhere to a uniform style when writing program code.

    If in the practice of using a programming language a more or less definite style of program design has developed, then it is recommended to use it if it does not contradict the standards adopted in the organization or the team in which the development is carried out.

The second important characteristic of a programming style is determined by how the developer uses the tools and capabilities provided by the programming language. The main recommendation regarding the use of language features is that you need to study and understand all the features of the language and avoid those that can reduce the clarity of the program, in particular those associated with poorly thought out or implemented features and depending on the implementation of various tricks.

9.Formal means of representation of control processes
in structured programs.

9.1. Block diagrams (structural diagrams) and their designs.

The following basic constructions are used to describe programs using block diagrams.

    Basic constructions for forming block diagrams

1) Block "Originator / terminator". Used to indicate the beginning and end of a structural diagram. Each circuit must begin and end with this construct.

2) Block "Process". It is used to designate one or more actions that ensure the change (processing) of data, their form of presentation or location. To improve the clarity of the diagram, several such blocks can be combined into one.

3) Block "Decision". Used to represent a control transfer operation in accordance with a given condition. For each such block, the actual condition (question) must be set, which determines the scheme further development the computational process, as well as possible results of checking this condition (answers) corresponding to the options for transferring control.

4) Block "Input / output". It is used to indicate operations related to data input or output. Individual logic devices or communication functions must correspond to individual blocks. Each block indicates the operation to be performed, the type of device or file, and the type of data involved in the exchange.

5) –6) Blocks "Predefined Process". Used to indicate subroutine calls. A block with a horizontal line is intended to describe calls to subroutines that were specially developed for the program and which are presented in the documentation by their structural diagram. A block with vertical lines denotes a call to subroutines external to the program, for example, those that are part of the operating system environment.

7) Block "Connector". It is used when, due to the large size, it is necessary to divide block diagram into several parts, placed on separate sheets of paper. In this case, at the end of one sheet, this block is placed, into which the connecting line enters, and at the beginning of the next sheet, the same block from which the connecting line comes out is used.

8) Block "Commentary". Allows you to include in the diagram the necessary explanations for certain blocks. A large number of such blocks can reduce the clarity of the structural diagram.

The disadvantage of block diagrams regarding the requirements of structured programming is that they allow the use of non-structured methods of transferring control in the diagrams, an example of which in a program is an early exit from a loop or the use of an unconditional jump operator of the GOTO type.

9.2.Flow-forms (flowcharts).

Flow forms are graphical notations designed to describe structured programs in nested constructs that eliminate the need for control flow lines and thus the ability to represent non-structured program transitions. Each form element corresponds to one control structure and is depicted in the form of a rectangle, which can be a component of another element and, in turn, include some other parts of the form. The original rectangle, which contains the entire shape, symbolizes the described program. Each form element contains text in natural or formal language that defines the purpose of that element. Below are the main constructions of Flow-forms used in the description of programs.

    Basic Flow Form Designs

9.3. Schemes (diagrams) of Nassi-Shneiderman.

Nassi-Schneiderman schemes are a development of Flow-forms. Their main difference is that in the blocks representing branching and selection, triangles are used to represent conditions, which makes it possible to achieve greater clarity in the description of the program. The basic constructions of Nassi-Schneiderman diagrams are given below.

    Basic constructions of Nassi-Schneiderman diagrams

The advantage of Flow-forms and Nassi-Schneiderman diagrams is that they allow you to clearly depict the nesting of structures. A common drawback of these graphical schemes is the complexity of describing with their help. large programs due to the bulkiness of the structures used for this.

10. An object-oriented approach to programming.

10.1 Basic concepts and principles of the object-oriented approach to programming.

The essence object approach consists in the predominant use of object decomposition for the description and construction of software. Moreover, the functions such software system are expressed through operations on objects of different levels of the hierarchy, i.e. their decomposition essentially depends on the decomposition of objects. Under object-oriented approach we mean an object approach with a focus on describing objects in the subject area and building their models, in which active objects are mainly used, that is, objects that include software parts that can be in the process of execution. The object-oriented approach to software development includes three main stages:

    Object Oriented Analysis. An object-oriented model of the domain of the software system is created, in which model objects represent real or conceptual entity objects, and also the operations performed on them are determined.

    Object oriented design. An object-oriented software model (system architecture) is being developed, taking into account the existing requirements, in which the definition of all objects is subordinated to the solution of a specific problem.

    Object Oriented Programming. The architecture (model) of the system is implemented using an object-oriented programming language.

Object-oriented representation and decomposition of a software system is based on the principles of abstraction, encapsulation, modularity and hierarchical organization. Abstraction comes down to the formation of abstractions. Each abstraction captures the basic characteristics of an object that distinguish it from other kinds of objects and provide clear conceptual boundaries. Abstraction focuses on the external representation of an object and allows you to separate the basic behavior of an object from its implementation. Encapsulation contains and hides the implementation of an object that provides its behavior. Encapsulation is achieved through informational closure. Usually the structure of objects and details of their implementation are hidden. Modularity determines the ability of the system to be decomposed into a number of strongly linked and weakly linked modules. Modules serve as physical containers in which software system components are declared. Modularity defines the way in which logically related abstractions are grouped. Hierarchical organization is designed to form a hierarchical structure from abstractions. Hierarchical organization defines the placement of abstractions on different levels system descriptions. Two important tools for hierarchical organization in OOP are: the isolation of the general-particular relationship and the whole-part relationship. Most often, the public-private hierarchy is built using inheritance. The whole-part hierarchy is based on an aggregation relationship.

10.2 Object-oriented approach to programming: the concept of an object and its characteristics, connections between objects.

An object is a concrete representation of abstraction. The class defines the structure and behavior of similar / similar objects, i.e. describes their abstraction. An object has personality, state and behavior. Individuality is a characteristic of an object that distinguishes it from all other objects. State object is a list of all its properties / attributes and the current values ​​of each of them. Behavior characterizes how an object affects (or is affected) other objects in terms of changes in its state and transmission of messages. The behavior of an object depends on its state and the set of operations corresponding to it. Operation represents a service that an entity offers for use. There are five types of operations on an object: modifier - changes the state of the object; selector - provides access to the state, but does not change it; iterator - provides access to the content of an object in parts, in a strictly defined order; constructor - creates an object and initializes its state; destructor - destroys the object and frees the resources it occupies. The execution of the operation ensures that the corresponding messages that can be sent to this object. Subroutines (methods) are the means of implementing operations. Thus, a message is a call to some subroutine that implements one of the operations inherent in the object. The set of routines that implement the operations of an object is called it protocol or interface (messages).

The interaction of objects depends on the relationship between them, which is based on mutual information about the allowed operations and the expected behavior. The most significant are two types of relationships between objects: links and aggregation. Connection is a physical or conceptual connection between objects. A relationship refers to a connection through which a client object invokes operations on a provider object (sends messages to it) or one object moves data to another object. There are four forms of visibility between objects: the provider object is global to the customer, the provider object is a parameter of the customer operation, the provider object is part of the customer object, and the provider object is a locally declared object in the customer operation. Aggregation represents relationships of objects in the whole-part hierarchy and provides the ability to move from the whole (aggregate) to its parts (properties). An object that is part (property) of another object (aggregate) has a relationship with its aggregate. Through this link, the unit can send messages to it. Aggregation can mean the physical occurrence of one object in another, but it does not have to.

10.3 Object-oriented approach to programming: the concept of a class and its characteristics, relations between classes.

Class- a description of a set of objects that share the same properties, operations, relationships and semantics. Any object is just an instance of a class. In the class, an external representation (interface) is distinguished and internal organization(implementation). Interface describes the capabilities (services) of the class, i.e. represents to the external environment an abstraction of a class, its "visible" appearance. An interface consists of operation declarations supported by class instances, type declarations, variables, constants, and exceptions that refine the abstraction that the class expresses. The interface can be divided into three parts: open or public ( public), the ads of which are available to all clients; protected ( protected), which declarations are available only to the class itself, its subclasses and friends; private or private ( private), the announcements of which are available only to the class itself and its friends. The state of an object is set in its class through the definitions of constants or variables placed in its protected or private part. Thus, they are hidden (encapsulated) and their changes do not affect clients. Implementation class reflects the features of its behavior. It includes a detailed description (implementation) of all operations defined in the interface of the class.

The abstractions of each subject area are in different relations with each other, as a result of which the structure of the classes of the system is formed. There are four main types of relationships between classes: association - fixes structural relationships, i.e. links between instances of classes; dependence - displays the influence of one class on another; generalization-specialization - relations "general-particular"; whole-part are aggregation / inclusion relations. To express these types of relationships, most object-oriented languages ​​support different combinations of the following types of relationships: association, inheritance, aggregation, dependency, instantiation, metaclass, implementation. Association denotes a semantic (semantic) two-way relationship between classes. It is the most general and indefinite relationship, since it does not indicate the direction and exact implementation of the relationship. Inheritance- a relationship in which one class shares the structure and behavior defined in another (single inheritance) or in several other classes (multiple inheritance). Inheritance is a kind of generalization-specialization relationship. The concept of polymorphism is associated with inheritance. Polymorphism is the ability to use one name to denote operations from different classes, but belonging to the same superclass. A service call by a polymorphic name results in the execution of one operation from a set corresponding to the class inheritance hierarchy. Relationship aggregations between classes are similar to those between objects. Addiction- a relationship that indicates that a change in one class (independent) can affect another class (dependent) that uses it. Dependency allows you to clarify which abstraction is the customer and which is the provider of a particular service. Concretization- the process of filling or customizing a template (generalized or parameterized class) in order to obtain a class from which it is possible to create instances. Concretization expresses another kind of generalization-specialization relationship. Metaclass- class of classes, i.e. a class whose instances are classes. Implementation- a relationship in which the receiving class provides its own implementation of the interface of another source class.

11. Defensive programming.

11.1 Concept of correct and reliable program... Basic concepts of reliable software development. Defensive programming concept.

The program is correct if it satisfies external specifications, i.e. returns expected responses to specific combinations of input data values. The program is reliable if correct, responds reasonably to imprecise inputs, and performs satisfactorily under unusual conditions.

In the process of creating a program, developers try to anticipate all possible situations and write the program so that it responds to them quite satisfactorily. Many principles and methods of software development (for example, structured and modular programming, abstract data types and encapsulation, etc.) to one degree or another pursue the goal of creating reliable programs, i.e. focused on reducing the likelihood of errors in the finished program and minimizing their impact. Since, in the general case, it is impossible to develop a program that would be absolutely reliable and would not contain errors, the necessary process is to check the correctness and reliability of the program. It includes reviewing the design documentation and the text of the program, analyzing the text of the program for errors and testing. The errors found based on the results of the check must be eliminated, after which it must be partially or completely re-executed.

Due to the fact that during the development of a program it is usually impossible to avoid all errors, it is advisable to include in the created software means of their detection. This allows you to minimize both the impact of the error on the operation of the program and subsequent difficulties for a person who will have to extract information about this error, find its place and fix it. After an error is detected, either it itself or its consequences must be corrected by the program, for which various methods can be used. Thus, the use of appropriate methods and tools allows the functioning of the software system in the presence of errors.

Programming, in which special techniques of warning, early detection and neutralization of errors are applied, is called protective or error-proof programming... These techniques focus on protecting programs and their components from incorrect inputs, and how to identify, isolate, and handle errors.

11.2 Types of errors associated with the original data, and how to protect against them.

The following types of errors associated with the original data are distinguished:

    Transfer errors- Caused by hardware that, for example, due to a malfunction, may falsify the data. Such errors are usually hardware controlled.

    Conversion errors- arise due to the fact that the program incorrectly converts data from the input format to the internal working one. To protect against such errors, the resulting input is usually shown directly to the user (called "echo output"). In this case, the conversion to the internal format is carried out first, and then back. However, it is usually quite difficult to prevent all conversion errors. Therefore, you should use other defensive programming techniques, and carefully work out and test the corresponding fragments of the program.

    Rewriting errors- due to the fact that the user makes a mistake when entering data, for example, enters an extra or another character. Such errors can be detected and corrected by using redundant data, such as checksums, and special restrictions on the values ​​and format of the input data, such as ranges of valid values. You should check the entered data in accordance with the established restrictions and, if there is an error, either automatically correct them, or prompt the user for new values.

    Data errors- caused by the fact that the user enters incorrect data. Such errors can usually only be detected by the user, so it makes sense during the input process to show him the entered data and ask for confirmation to perform further operations, especially in cases where it will be impossible to correct incorrect information in the future.

11.3 The main ways to prevent errors.

Basic concepts for preventing errors in a running program include:

    checking the correctness of input data and input-output operations;

    checking the admissibility of intermediate results;

    preventing the accumulation of errors.

These ideas are aimed at controlling the correctness of the original or intermediate data of the program. Invalid data may appear as a result internal error errors such as errors in I / O devices or software, or as a result of an external error such as a user error or an associated program.

One defensive programming technique is to isolate errors that can arise from incorrect input data. For this purpose, a specialized programming interface can be developed (for example, a set of subroutines that process input data), used as a kind of "protective" shell for the rest of the code. Data validation and processing of corresponding errors is carried out at the level of this interface and data passed through it are considered safe in the future. The same approach applies at the level of an individual module or class. Public routines of a module or class assume that data may contain errors and are responsible for checking and correcting them. If the data has been validated with public methods, private methods can treat it as safe.

Checking intermediate results allows you to reduce the likelihood of late manifestation of not only incorrectly defined data errors, but also some errors made at the design and coding stage. To organize such a check, it is necessary to use variables in the program for which there are restrictions of any kind, for example, those associated with the peculiarities of the subject area. However, you should take into account the fact that any additional operations require the use of additional resources (for example, time or memory) and may also contain errors. Therefore, it is advisable to check intermediate results only in those cases when it is not difficult and really allows you to detect errors. For example:

    the value of the input parameter of the subroutine lies in the specified numerical range or coincides with one of the predefined values;

    array element index is within acceptable limits;

    the value of the variable that determines the number of loop iterations is not negative;

    the required file exists or could be opened for reading / writing;

    the file pointer is at the beginning or end, etc.

To reduce the errors in the calculation results, it is recommended:

    avoid subtracting close numbers (machine zero);

    avoid division large numbers small;

    start adding a long sequence of numbers from those that have a lower absolute value;

    do not use the condition of equality of real numbers;

    strive to reduce the number of transactions as much as possible;

    apply methods with known error estimates;

    information Abstract

    Schemes technological processes... Technology automated processing information is based on the following principles ... cycle informationsystemsConcept life cycle is one of the basic concepts design methodology information ...

Hello dear novice programmers.

You probably already understand from previous articles that a program consists of expressions, strings, numbers, operators, functions that are executed in a specific sequence.

The programmer sets the order of program execution, and for this he applies the control structures of the language. That is, a control structure is a command for one or another order of program execution.

Before proceeding to the description of control structures, I must warn you that you will see many familiar names, since the structure can be operators, functions, loops, which we have already discussed in previous articles.

Constructions (definitions are possible - instruction, command) can be either one-line or compound, that is, assembled into a block. The block is also a separate structure, consistently performing the constructions that are enclosed in it.

There are six main groups of control constructs in PHP. It:

1. Conditional operators.
2. Cycles.
3. Designs of choice.
4. Constructions of the announcement.
5. Constructs to return values.
6. Constructions of inclusions.

Let's look at them in detail, and everything in order.

Conditional Operators

We have already met the conditional operators if, else, elseif in the article “ Php statements", So now, considering them as control constructions, we will get a repetition of what we have passed, which, as you know, is never superfluous.

Conditional operators are the most commonly used constructs, not only in php, but in all algorithmic programming languages.

One line example if statements

if ($ next == 0)
{
echo "This is a programming language construct";
}
?>

In this example if statement, the condition is given: the variable $ next must be equal to zero. If this condition is true, then echo will be executed. If not, it will open empty page.

The following will be an example of a composite construction.

$ next = 0;
if ($ next == 0)
{
echo $ vegetables. "Vegetables
";
echo $ fruit. " Fruits
";
echo $ berries. " Berries
";
}
?>

Here, the $ next variable is also assigned the value 0, and the if statement, after checking it, executes the echo block of constructs.

Please note that for line breaks in php, the familiar to us from html tag is used
... In the future, we will meet more than once html tags used in php code.

And I also note that the indentation in php values do not have, and only code readability improvements are applied.

In the previous example, we considered the option when the statement is executed if the specified condition is true.

Now imagine that we need to execute some operator not only when the condition of the if statement is true, but also when the condition is not true.

In this case, the else construct

$ next = 1;
if ($ next == 0)
{
echo $ vegetables. "Vegetables";
}
else
{
echo $ fruit. "Fruits";
}
?>

In this case, it is not a blank page that opens, but the "Fruit" entry.

Elseif construct

This construct further expands the capabilities of the if and else constructs. Imagine we have more than two statements, one of which needs to be executed.

In this case, the elseif construction is added to the previous constructions.

$ next = 0;
if ($ next == 0)
{
echo $ vegetables. "Vegetables";
}
elseif ($ next == 0)
{
echo $ fruit. "Fruits";
}
else
{
echo $ berries. "Berries";
}
?>

In theory, there is no limit to the number of elseifs. And no matter how many there are, the program will check each one until it finds the correct one, that is, true.

Selection constructs

Very often, with a large number of operators, the use of the elseif construction becomes inconvenient due to the large amount of code.

In this case, comes to the rescue switch-case construct, you can switch switch

The switch-case construction is similar in its action to the if-else construction, but unlike the latter, it allows you to get more than two options as a result.

The body of the construct is enclosed in curly braces, and a colon-terminated case statement and a terminating break statement are applied for each value to be processed.

$ next = "Fruit";
switch ($ next) (
case "Vegetables":
echo "Potatoes";
break;
case "Fruit":
echo "Apples";
break;
case "Berries":
echo "Cherry";
break;
}
// Apples are displayed

In this example, the condition will be processed first, then a case statement with a value matching this condition will be found, and only after that the switch construction will start executing.

For values ​​not specified in the assignment, in the switch-case construction, the default statement is used.

$ next = "Mushrooms";
switch ($ next) (
case "Vegetables":
echo "Potatoes";
break;
case "Fruit":
echo "Apples";
break;
case "Berries":
echo "Cherry";
break;
default:
echo "Champignons";
}
// Champignons are displayed
?>

If you omit the break statement, then the program will process and display all values ​​of the switch-case construction

$ next = "Vegetables";
switch ($ next) (
case "Vegetables":
echo "Potatoes";
case "Fruit":
echo "Apples";
case "Berries":
echo "Cherry";
default:
echo "Champignons";
}
/ * Output
Potato
Apples
Cherry
Champignon */

?>

Another feature of the switch-case construction is the ability to combine several options into one expression.

$ next = "Maple";
switch ($ next) (
case "Vegetables":
case "Fruit":
case "Berries":
echo "Potatoes
Apples
Cherry";
break;
case "Maple":
case "Oak":
case "Spruce":
echo "Forest";
break;
default:
echo "Champignons";
}
// The Forest is displayed
?>

Loops, or repetition constructs.

Loops are intended for multiple (as opposed to the if construct) execution of the statements that make up the body of the construct.

The process of executing a loop is called iteration (iteration).

There are three kinds of loops in php:

1. while and do-while are loops with an undefined number of iterations.
2. for - a loop with a predetermined number of iterations.
3. foreach - a loop for processing (iterating over) an array.

While construct

An example of the simplest loop with one operator, usually there are more of them.

$ next = 1;
while ($ next<= 8 )
{
echo $ next. "
" ;
$ next ++;
}
// Prints numbers from 1 to 8. Tag
positions them in a column

?>

Let's take a closer look at what is happening here, that is, how this program works.

The first line declares the variable $ next, which is assigned the value one. Assigning a value is called variable initialization.

On the second line, the program checks the condition while ($ next<= 8) , которое будет являться истиной (true).

The third line executes the first loop, since the one is less than 8, and this matches the definition of true

In the fourth, the variable, which in this case is an operator, is assigned the increment operator (++), which increments each subsequent value of the $ next operator by one.

And the program will process and display each integer following one until it reaches 9. And since 9 turns out to be false, the loop ends.

Do-while construct differs in that the loop condition is checked not before, but after the iteration.

As a result, before the end of the loop, one iteration must be executed, which is false.

$ next = 1;
do
{
echo $ next;
}
while ($ next ++<= 8 );
// Prints numbers from 1 to 9 on one line.
?>

As you can see, although 9 is false, the next iteration was still performed, after which the program checked the condition and the loop ended.

The for construct, or a loop with a counter, in its work is similar to a while loop, but has a more compact form of notation.

It is used better when the number of iterations is known before the start of the loop, and with the help of it, you can perform actions more complex than a simple iteration of the counter values.

In the following example, we will write a table of contents for a small book.

for ($ next = 1; $ next< 5 ; $next++)
{
echo "- Page". $ next. "
";
}
/ * Outputs
-Page 1
-Page 2
-Page 3
-Page 4
-Page 5 * /

?>

Let's consider in detail the three expressions written in the condition (parentheses) of the loop.

$ next = 1; - variable counter, starting counting from one.
$ next< 5; — определяет продолжительность цикла.
$ next ++ - determines the step of changing the counter value. In our case, it is equal to one.

Expressions are separated by semicolons. You can put several commands in one expression and separate them with commas. Then the same table of contents can be done a little differently.

for ($ next = 1 , $ nev = 1 , $ page = "-Page"; $ next<= 5 ; $nev++, $next=$nev)
{
$ page = $ page. "-";
echo $ page, $ next. "
";
}
/ * Outputs
-Page-1
-Page - 2
-Page --- 3
-Page ---- 4
-Page ----- 5 * /

?>

Another feature of for is the ability to do without echo.

True, this option is not particularly welcome, since it somewhat complicates the readability of the code, due to its unusualness, but it still has a right to exist.

In it, the print construct is entered into the loop condition

for ($ next = 1; $ next<= 5 ; print $next, print "
", $ next ++);
/ * Outputs
1
2
3
4
5 */

?>

The echo construct cannot be entered into the for clause.

All of the above constructs, except for do-while, have an alternative notation - without curly braces.

In this case, the line with the construct and the condition ends with a colon, and the entire block is closed with an end construct, the continuation of which is the construct to which it is applied: endif, endwhile, and so on.

$ next = 1;
while ($ next<= 10 ):
echo $ next;
$ next ++;
endwhile;
?>

Foreach construct Is a special type of loop designed only for iterating over an array.

$ next ["tomato"] = "Red";
$ next ["apple"] = "green";
$ next ["grapes"] = "Sweet";
$ next ["mushroom"] = "White";
foreach ($ next as $ key => $ value)
{

echo "$ value $ key
";
}
/ * Outputs
Red tomato
Green apple
Sweet grapes
White mushroom */

?>

To exit the loop immediately, if necessary, there is break construct... After its execution, control is transferred to the expression following the loop.

$ next = 0;
while ($ next ++< 10 )
{
if ($ next == 7) break;
echo "$ next
";
}
/ * Outputs
1
2
3
4
5
6 */

?>

As you can see, on the seventh iteration, the loop was interrupted.

The continue construct, unlike break, only interrupts the current iteration and moves on to the next.

$ next = 0;
while ($ next ++< 5 )
{
if ($ next == 3) continue;
echo "$ next
";
}
/ * Outputs
1
2
4
5 */

?>

As you can see, iteration 3 is missing, since it was interrupted by the continue statement.

Declaration constructs

Declaration constructs in php are represented by two elements. These are declare and typeset constructs.

In fact, they are absolutely identical, and both one and the other can be used with equal success to obtain the same result.

For the convenience of understanding the code, the declare construction is mainly used. It is used to set commands (directives) for block execution.

Currently, two directives are recognized - they are ticks and encoding.

The ticks directive sets the number of ticks

declare (ticks = 1);

register_tick_function ("tick_handler");

// Function, will be executed at every tick
?>

The encoding directive is used to specify the encoding of the entire script.

declare (encoding = "UFT-8");
?>

Inclusion constructions

Inclusion constructs are used to inject individual scripts and files into a program. Thanks to them, the program can be assembled from ready-made material.

Inclusion constructions are also used to reduce the amount of script code when you need to enter some text into the code. Then the txt file is entered into the program.

True, in this case, there is a threat to the security of the script, and to solve it, together with the txt file, you must enter a constant into the program, and check its existence in the included files.

There are 4 types of containment constructs in php, and they all accept only one argument - the path to the file:

include - includes the file to the program, if it is absent, it issues a warning;
require - connects the file to the program, if it is absent, the script stops working;
include_once - allows only one-time inclusion of an included file, and if it is absent, it issues a warning;
require_once - allows only one-time inclusion of the included file, and if it is absent, the script stops working;

The include_once and require_once constructs are convenient in that they avoid confusion with nested includes, when it is possible to re-include files containing function declarations.

Are there really no questions left?


Turn

Only here the word "yeah" is synonymous with the words "please", "thank you", "good afternoon", "nothing for that" and "sorry", and the word "come on" in most cases replaces "goodbye".

You don't expect any love like a bus at -30 °.

Language syntax Transact SQL includes two main types of governing structures. These are the operators: if, while... Each of these structures has corresponding restrictions and requirements for their writing in terms of standards. There are also some general requirements for all these structures. All these requirements and restrictions are formed based on the principles of easy subsequent readability of the source code.

Rules for writing control structures

The whole source located inside control structures, as well as nested logical structures, must be indented by 2 characters.

It is not allowed to use other instructions together with the control one on the same line.

4.2.1.3 The “begin end” construction must always start on a new line.

Nesting of control structures is allowed, except for explicitly specified exceptions.

Conditional IF statement

Format:

It is also allowed to write:

Format: if [boolean expression 1]

All parts of the conditional operator (if, else if, else, begin, end) must be positioned starting from the same position

4.2.2.2 Inside the "logical brackets" of a conditional statement, Transact SQL statements must be nested according to the standard tab of 2 characters

When writing logical operators in logical expressions, you must put spaces before and after them

When writing complex logical expressions, it is forbidden to insert spaces between brackets and part of a logical expression

WHILE control structure

Format: while ([condition for continuing the loop])

(operators)

4.2.3.1 Within the "logical brackets" of a while structure, Transact SQL statements must be nested according to the standard tab of 2 characters

The use of the while structure is central to organizing the various passes with cursor.


Basic Operators

Transact SQL syntax includes five main operators. These are the operators: select, insert, update, delete, cursor... Each of these operators has corresponding restrictions and requirements for their writing in terms of standards. There are also some general requirements for all these operators. All these requirements and restrictions are formed based on the principles of easy subsequent readability of the source code.

Any PHP script is formed from a number of constructs. A construct can be operators, functions, loops, conditional operators, even constructs that do nothing (empty constructs). Constructs usually end with a semicolon. In addition, structures can be grouped into a group, forming a group of structures with curved curly braces (...). A group of structures is also a separate structure. PHP constructs are similar to C constructs.

There are six main groups of control constructs in PHP. So, the main groups of PHP control structures and their composition:

  • Conditional operators:
    • else
    • elseif
  • Cycles:
    • while
    • do-while
    • foreach
    • break
    • continue
  • Selection designs:
    • switch-case
  • Declaration constructions:
    • declare
    • return
  • Inclusion constructions:
    • require ()
    • include ()
    • require_once ()
    • include_once ()
  • Alternative syntax for PHP constructs

PHP conditional statements

Conditional statements are perhaps the most common construct in all algorithmic programming languages. Let's take a look at the basic conditional operators of the PHP language.

If statement

The syntax of the if statement is similar to the if statement in the C language:

According to PHP expressions, the if construct contains a boolean expression. If the boolean expression is true (true), then the statement following the if statement will be executed, and if the boolean expression is false (false), then the statement following the if will not be executed. Here are some examples:

$ b) echo "the value of a is greater than b"; ?>

In the following example, if the variable $ a is non-zero, the string "the value of a is true" will be output:

"the value of a is true"; ?>

In the following example, if the variable $ a is equal to zero, the string "the value of a is false" will be displayed:

"the value of a is false"; ?>

Often you will need a block of statements that will be executed under a certain conditional criterion, then these statements must be enclosed in curly braces (...) Example:

$ b) (echo "a is greater than b"; $ b = $ a;)?>

The above example will print the message "a is greater than b" if $ a> $ b, and then the variable $ a will be set to the variable $ b. Note that these statements are executed in the body of the if statement.

The else construct

Often there is a need to execute statements not only in the body of the if statement, if any condition of the if statement is met, but also if the condition of the if statement is not met. In this situation, you cannot do without the else construct. In general, such a construction will be called an if-else construction.

The syntax for the if-else construction is as follows:

If (boolean_expression) statement_1; else statement_2;

The action of the if-else construction is as follows: if logical_expression is true, then instruction_1 is executed, otherwise - instruction_2. As in any other language, the else clause can be omitted, in which case nothing is done when the proper value is obtained.

If instruction_1 or instruction_2 must consist of several instructions, then they are, as always, enclosed in curly braces. For example:

$ b) (echo "a is greater than b";) else (echo "a is NOT greater than b"; } ?>

The if-else construct has another alternative syntax:

If (boolean_expression): commands; elseif (other_boot_expression): other_commands; else: else_commands; endif

Pay attention to the location of the colon (:)! If you skip it, an error message will be generated. And one more thing: as usual, the elseif and else blocks can be omitted.

Elseif construct

elseif is a combination of if and else statements. This construct extends the conditional if-else construct.

Here is the syntax for the elseif construction:

If (boolean_expression_1) operator_1; elseif (boolean_expression_2) operator_2; else operator_3;

A practical example of using the elseif construct:

$ b) (echo "a is greater than b";) elseif ($ a == $ b) (echo "a is equal to b";) else (echo "a is less than b";)?>

In general, the elseif construction is not very convenient, so it is not used very often.

Cycles:

In second place in terms of frequency of use, after conditional statements (conditional operators), are loops.

Loops allow you to repeat a certain (and even indefinite - when the work of the loop depends on the condition) number of times different operators. These operators are called the body of the loop. Walking through the loop is called iteration.

PHP supports three kinds of loops:

  1. Loop with a precondition (while);
  2. Loop with postcondition (do-while);
  3. Loop with a counter (for);
  4. A special loop through arrays (foreach).

When using loops, it is possible to use the break and continue statements. The first one interrupts the entire cycle, and the second one - only the current iteration.

Consider PHP loops:

Loop with while precondition

A while loop works according to the following principles:

  • The value of the logical expression is evaluated.
  • If the value is true, the body of the loop is executed, otherwise, go to the next statement after the loop.

"The syntax for a loop with a precondition is: "

While (boolean_expression) statement;

In this case, the body of the loop is an instruction. Typically, the body of a loop consists of a large number of statements. Here is an example of a loop with a while precondition:

Pay attention to the sequence of operations of the condition $ x ++<10. Сначала проверяется условие, а только потом увеличивается значение переменной. Если мы поставим операцию инкремента перед переменной (++$x<10), то сначала будет выполнено увеличение переменной, а только затем - сравнение. В результате мы получим строку 123456789. Этот же цикл можно было бы записать по-другому:

// Increase the counter echo $ x; ) // Prints 12345678910?>

If we increment the counter after executing the echo statement, we get the string 0123456789. Anyway, we have 10 iterations. Iteration is the execution of statements within the body of a loop.

Similar to the construction of a conditional if statement, you can group statements within the body of a while loop using the following alternative syntax:

While (boolean_expression): statement; ... endwhile;

An example of using alternative syntax:

Loop with postcondition do while

Unlike the while loop, this loop checks the value of the expression not before, but after each pass (iteration). Thus, the body of the loop is executed at least once. The syntax for a loop with a postcondition is as follows:

Do (loop-body;) while (boolean_expression);

After the next iteration, it is checked whether the logical_expression is true, and, if so, control is transferred again to the beginning of the loop, otherwise the loop is terminated. PHP developers have not provided an alternative syntax for do-while (apparently, due to the fact that, unlike application programming, this loop is rarely used when programming web applications).

An example of a script showing the operation of a loop with a do-while postcondition:

12345678910

For loop

A counter loop is used to execute the loop body a specified number of times. Using a for loop, you can (and should) create constructs that will perform actions that are not at all as trivial as a simple iteration over the counter value.

The syntax for a for loop is:

For (initialization_commands; loop_condition; post_iteration_commands) (loop-body;)

The for loop begins by executing initialization_commands. These commands are executed only once. After that, the loop_condition is checked, if it is true, then the loop-body is executed. After the last statement of the body is executed, the after_iteration_commands are executed. Then the loop_condition is checked again. If true, the loop-body and the post-iteration commands are executed, and so on.

This script outputs: 0123456789

There is a variant of outputting the line 12345678910:

In this example, we have ensured that the counter is incremented when testing a boolean expression. In this case, we did not need the commands that are executed after the iteration.

If you need to specify several commands, they can be separated by commas, example:

Here's another, more practical example of using multiple commands in a for loop:

// Outputs Points. Points ... Points ... Points .... ?>

The considered example (and indeed any for loop) can be implemented through while, only it will look less elegant and laconic.

There is also an alternative syntax for the for loop:

For (initialization_commands; loop_condition; post_iteration_commands): statements; endfor;

Foreach array iteration loop

PHP4 introduces another special type of loop - foreach. This loop is designed specifically for iterating over arrays.

The syntax for a foreach loop is as follows:

Foreach (array as $ key => $ value) commands;

Here the commands are cyclically executed for each element of the array, while the next key => value pair appears in the $ key and $ value variables. Here's an example of how the foreach loop works:

$ value) (echo " $ value $ key
" ; } ?>

The considered script outputs:

Andrey Ivanov Boris Petrov Sergey Volkov Fedor Makarov

The foreach loop has another notation that should be used when we are not interested in the key value of the next item. It looks like this:

Foreach (array as $ value) commands;

In this case, only the value of the next element of the array is available, but not its key. This can be useful, for example, for working with arrays-lists:

$ value
"
; } ?>

Attention: Foreach loop operates not on the original array, but on its copy. This means that any changes that are made to the array cannot be "visible" from the body of the loop. That allows, for example, to use not only a variable as an array, but also the result of the operation of some function that returns an array (in this case, the function will be called only once - before the start of the loop, and then the work will be performed with a copy of the returned value).

Break construct

Very often, in order to simplify the logic of a complex loop, it is convenient to be able to interrupt it during the next iteration (for example, when some special condition is met). For this, there is a break construction, which immediately exits the loop. It can be specified with one optional parameter - a number that indicates from which nested loop should be exited. The default is 1, which exits the current loop, but sometimes other values ​​apply. The break syntax is:

Break; // By default break (cycle_number); // For nested loops (the number of the interrupted loop is indicated)

Here are some examples:

Iteration $ x
"
; } // When $ x is 3, the loop breaks ?>

The considered script outputs:

Iteration 1 Iteration 2

If we need to interrupt the work of a certain (nested) loop, then we need to pass a parameter to the break structure - loop_number, for example, break (1). Cycles are numbered as follows:

For (...) // Third cycle (for (...) // Second cycle (for (...) // First cycle ()))

The continue construct

The continue construction, like break, works only "in tandem" with looping constructs. It immediately ends the current iteration of the loop and moves on to a new one (of course, if the loop condition is satisfied for the loop with a precondition). In the same way as for break, for continue, you can specify the level of nesting of the loop, which will be continued upon return of control.

Basically continue allows you to save the amount of curly braces in your code and increase readability. This is most often needed in filter loops, when you need to iterate over a certain number of objects and select from them only those that satisfy certain conditions. Let's give an example of using the continue construct:

Iteration $ x
"
; } // The loop will only interrupt at the third iteration ?>

The considered script outputs:

Iteration 1 Iteration 2 Iteration 4 Iteration 5

Smart use break and continue allows you to noticeably improve the "readability" of the code and the number of else blocks.

Selection designs:

Often, instead of several consecutive if-else statements, it is advisable to use the special switch-case selection construct. This construction is designed to select actions, depending on the value of the specified expression. The switch-case construction is somewhat reminiscent of the if-else construction, which, in fact, is its analogue. The choice construct can be used if there are many suggested options, for example, more than 5, and specific actions need to be performed for each option. In this case, using the if-else construct becomes really awkward.

The syntax for the switch-case construct is as follows:

Switch (expression) (case value1: commands1; case value2: commands2;... Case valueN: commandsN;])

The principle of operation of the switch-case construction is as follows:

  • The value of the expression is calculated;
  • A set of values ​​is viewed. Let value1 be equal to the value of the expression calculated in the first step. If the structure (operator) break is not specified, then the commands i, i + 1, i + 2, ..., N will be executed. Otherwise (there is a break), only the command with the number i will be executed.
  • If none of the values ​​in the set match the value of the expression, then the default block, if specified, is executed.

Here are examples of using the switch-case construction:

// Use if-else if ($ x == 0) (echo "x = 0
";) elseif ($ x == 1) (echo" x = 1
";) elseif ($ x == 2) (echo" x = 2
" ; } // Use switch-case switch ($ x) (case 0: echo "x = 0
"; break; case 1: echo" x = 1
"; break; case 2: echo" x = 2
"; break;)?>

The above script prints x = 1 twice. Another example of using the switch-case construction:

This script displays "This is an Apple".

The switch construct is performed in stages. At first, no code is executed. Only when a case construct is found with a value that matches the value of the switch expression does PHP start executing the constructs. PHP continues to execute constructs until the end of the switch block, until a break statement is encountered. If you do not use the break constructs (operators), the script will look like this:

"; case 1: echo" x = 1
"; case 2: echo" x = 2
" ; } // Without using break outputs// x = 0 // x = 1 // x = 2?>

The statement list for case can also be empty, it simply transfers control to the statement list until the next case statement:

"x is less than 3, but not negative"; break; case 3: echo "x = 3"; )?>

When no value from the set matches the value of the expression, then the default block is executed, if specified, for example:

"x is not 0, 1, or 2"; } ?>

This script outputs "x is not 0, 1 or 2" because the variable $ x = 3.

The switch-case construct also has an alternative syntax:

Switch (expression): case value1: commands1; ... ... ... case valueN: commandsN; ] endswitch;

A practical example of using an alternative syntax for the switch-case construction:

"x is not 0, 1, or 2"; endswitch; ?>

As you already understood, this script outputs "x is not equal to 0, 1 or 2", since $ x = 3.

Ads constructions:

Declare construct

The declare construct is used to set execution directives for a block of code. The declare syntax is similar to that of other PHP control constructs:

Declare (directive) statement;

The directive allows you to set the behavior of the declare block. Currently, there is only one directive available in PHP - tick. The statement is part of the declare block.

How the instruction (s) will be executed depends on the directive.

Design declare can be used in the global scope, affecting all code after it.

Tick ​​directive

tick is an event that occurs for every N low-level instructions executed by the parser within a block declare... The events that occur at each tick are determined by the function register_tick_function ().

Return value constructs:

Return construct

The rerurn construct returns values, primarily from UDFs, as parameters to a function request. When return is called, the execution of the user-defined function is interrupted, and the return construct returns certain values.

If the return construct is called from the global scope (outside of user-defined functions), then the script will also terminate its work, and return will also return certain values.

Mostly, the return construct is used to return values ​​by user-defined functions.

Return values ​​can be of any type, including lists and objects. A return terminates the execution of the function and transfers control back to the line of code in which this function was called.

An example of using the return construct to return integer values:

An example of returning arrays by the return construction:

In order for a function to return a result by reference, you need to use the & operator both when describing the function and when assigning a return value to a variable:

As we can see, the construction return very convenient for use in custom functions.

Inclusion constructions:

Inclusion constructs allow you to build a PHP program (script) from several individual files.

There are two main constructs of inclusions in PHP: require and include.

The require include construct

The require clause allows you to include files in a PHP script before the PHP script is executed. The general syntax for require is:

Require filename;

At startup (exactly at startup, not at execution!) Of the program, the interpreter will simply replace the instruction with the contents of the file filename (this file may also contain a PHP script, framed, as usual, with tags). Moreover, he will do this immediately before starting the program (as opposed to include, which is discussed below). This can be quite handy for including various template pages in HTML code in the script output. Let's give an example:

Header.html file:

It is a title

Footer.html file:

Home Company, 2005.

Script.php file

// The script outputs the body of the document itself require "footer.htm"; ?>

Thus, the require construct allows you to collect PHP scripts from several separate files, which can be both html pages and php scripts.

The require clause supports including remote files (since PHP 4.3.0). For example:

// The following example works require; ?>

The require construct allows you to include deleted files, if this feature is enabled in the configuration PHP file. detailed information Further.

Include constructs

The include construct is also intended to include files in your PHP script code.

Unlike the require construct, the include construct allows you to include files in your code. PHP script during script execution. The syntax for the include construct is as follows:

Include filename;

Let us explain the fundamental difference between require and include constructions with a specific practical example. Let's create 10 files with the names 1.txt, 2.txt and so on up to 10.txt, the contents of these files are just decimal digits 1, 2 ... ... 10 (one digit in each file). Let's create a PHP script like this:

// Create a loop, in the body of which the include construction for ($ i = 1; $ i<= 10 ; $i ++ ) { include "$ i .txt "; } // Included ten files: 1.txt, 2.txt, 3.txt ... 10.txt // Result - output 12345678910 ?>

As a result, we get an output consisting of 10 digits: "12345678910". From this we can conclude that each of the files was included one time right during the execution of the loop! If we now put require instead of include, the script will generate a fatal error. Compare the result.

PHP converts the script to its internal representation by parsing the lines of the script one by one until it comes to the include clause. Upon reaching include, PHP stops translating the script and switches to the file specified in the include. Thus, due to this behavior of the translator, the script performance decreases, especially with a large number of files included with include files. With require, there are no such problems, since files are included using require before the script is executed, that is, at the time of translation, the file is already included in the script.

Thus, it is more expedient to use the require construction where there is no need to dynamically include files in the script, but include construct use only for the purpose of dynamically including files in the PHP script code.

Design include supports including remote files (since PHP 4.3.0). For example:

// The following example doesn't work because it tries to include a local file// The following example works include "http://www.example.com/file.php?foo=1&bar=2"; ?>

The include clause allows you to include remote files, if enabled in the PHP configuration file. More details below.

The one-time include constructs require_once and include_once

In large PHP scripts, include and require statements are used very often. Therefore, it becomes quite difficult to control not to accidentally include the same file several times, which often leads to an error that is difficult to detect.

PHP provides a solution to this problem. By using the one-time include constructs require_once and include_once, you can be sure that the same file will not be included twice. The one-time include constructs require_once and include_once work in the same way as require and include, respectively. The only difference in their work is that before including the file, the interpreter checks whether specified file earlier or not. If so, the file will not be included again.

The one-time include constructs also require_once and include_ince also allow remote files to be included if enabled in the PHP config file. More details below.

Includes remote files

PHP allows you to work with URL objects like regular files. The default packers are used to work with remote files using ftp protocol or http.

If "URL fopen wrappers" are included in PHP (as in the default configuration), you can specify the file to be included using a URL (over HTTP) instead of a local path. If the target server interprets the target file as PHP code, variables can be passed to the include file using a URL query string, as in HTTP GET. Strictly speaking, this is not the same as including a file and inheriting the variable scope of the parent file; because the script runs on a remote server, and the result is then connected to the local script.

In order for remote inclusion of files to be available, set allow_url_fopen = 1 in the configuration file (php.ini).

Note: PHP versions Windows prior to PHP 4.3.0 do not support the ability to use remote files with this feature even if the allow_url_fopen option is enabled.

/ * This assumes www.example.com is configured to parse .php * files, not .txt files. Also "Works" here means that the variables * $ foo and $ bar are available in the included file. * / // Will not work as file.txt is not being processed by www.example.com as PHP include "http://www.example.com/file.txt?foo=1&bar=2"; // Will not work because it is looking for the file "file.php? Foo = 1 & bar = 2" in the local // file system. include "file.php? foo = 1 & bar = 2"; // The following example works: include "http://www.example.com/file.php?foo=1&bar=2"; $ foo = 1; $ bar = 2; include "file.txt"; // Works include "file.php"; // Works?>

See also remote files for fopen () and file () to get additional information.

Additionally:

You probably already know how to insert HTML code into the body of a script. To do this, you just need to close the brace?>, The code, and then reopen it with

You may have noticed how ugly it looks. However, if you put in a little effort to decorate it, it doesn't turn out to be all that bad. Especially if you use the alternative syntax of if-else and other language constructs.

More often than not, you do not need to insert HTML into the script, but rather insert code into the HTML. This is much easier for a designer who, perhaps, in the future wants to redesign the script, but will not be able to figure out what to change and what not to touch. Therefore, it is advisable to separate the HTML code from the program (script), for example, to place it in a separate file, which is then connected to the script using the include structure. For example, here's what a script would look like that greets a user by name, using the alternative if-else syntax:

Hey, !

method = get> Your name:

Agree that even a person who is completely unfamiliar with PHP, but who is well versed in HTML, can easily figure out what's what in this scenario. Consider an alternative syntax for some constructs in the context of using it in conjunction with HTML:

Alternative syntax for if-else

... HTML code ...... HTML code ...

Alternative syntax for while loop

... HTML code ...

An example of using an alternative syntax for a while loop:

As we can see, the use of alternative syntax makes PHP scripts readable in cases where it is necessary to actively manipulate PHP together with HTML code.

Annotation: The control structures of the C language are considered: branches "if-else" and "if-else if", loops "while" and "for". There are also constructions that should be avoided: "switch", "do-while", "goto". The presentation of the program in the form of a set of functions, prototypes of functions, methods of transferring input and output parameters are considered. Various types of memory are enumerated: static, stack, dynamic (heap) and ways of working with memory in C. The composite data type "structure" is introduced. The material is illustrated by numerous examples of programs: solving a quadratic equation, calculating the square root, calculating the GCD of two numbers and the extended Euclidean algorithm, printing the first N primes, recursive tree traversal, etc.

Control constructs

Control constructs allow you to organize loops and branches in programs. There are only a few constructs in C, and half of them can be omitted (they are implemented through the rest).

Braces

Curly braces allow you to combine several elementary operators into one compound operator, or block. In all syntactic constructions, a compound operator can be used instead of a simple one.

In C, you can place local variable declarations at the beginning of a block. Local variables described within a block are created when the block is entered and destroyed when the block is exited.

In C ++, local variables can be declared anywhere, not just at the beginning of a block. However, just like in C, they are automatically destroyed when the block is exited.

Here is a fragment of the program that exchanges the values ​​of two real variables:

double x, y; ... ... ... (double tmp = x; x = y; y = tmp;)

Here, to swap the values ​​of two variables x and y, we first store the value of x in an auxiliary variable tmp. Then x is written to the value of y, and y is the previous x value stored in tmp. Since the tmp variable is only needed inside this snippet, we enclosed it in a block and declared the tmp variable inside this block. On exit from the block, the memory occupied by the tmp variable will be freed.

If statement

The if statement ("if") allows you to organize branching in the program. It has two forms: the "if" operator and the "if ... otherwise" operator. The "if" operator has the form

if (condition) action;

the operator "if ... otherwise" has the form

if (condition) action1; else action2;

Any boolean or integer expression can be used as a condition. Recall that when using an integer expression, true is any nonzero value. When the "if" statement is executed, the conditional expression after the if is evaluated first. If it is true, then the action is performed; if it is false, then nothing happens. For example, in the following fragment, the maximum of the values ​​of the variables x and y is written to the variable m:

double x, y, m; ... ... ... m = x; if (y> x) m = y;

When the operator "if ... otherwise" is executed, in the case when the condition is true, the action written after the if is executed; otherwise, the action after else is performed. For example, the previous snippet is rewritten as follows:

double x, y, m; ... ... ... if (x> y) m = x; else m = y;

When you need to perform several actions depending on the truth of the condition, you should use curly braces, combining several operators into a block, for example,

double x, y, d; ... ... ... if (d> 1.0) (x / = d; y / = d;)

Here the variables x and y are divisible by d only if d is greater than one.

Curly braces can be used even when there is only one statement after the if or else. They improve the structure of the text of the program and facilitate its possible modification. Example:

double x, y; ... ... ... if (x! = 0.0) (y = 1.0;)

If we need to add another action that is performed on the condition "x is nonzero", then we simply add a line inside the curly braces.

Choice of several possibilities: if ... else if ...

Several conditional statements like "if ... otherwise" can be written sequentially (ie, the action after else can again be a conditional statement). As a result, it is realized choice from several possibilities... The choice construct is used very often in programming. Example: given a real variable x, you need to write the value of the function sign (x) to the real variable y.