Computers Windows Internet

Functions and their possibilities in programming. Software function and software aspect. Functions of two or more arguments

The loop operator is the most important operator and is found in most modern programming languages, and the very idea of ​​a loop originated in the 19th century. A loop allows you to repeatedly perform a certain sequence of actions, which is set by the operators that make up the body of the loop.

Let's start with the operator loop with precondition... This operator has the form:

While<условие>do<оператор>.

When this operator is executed, the value of the logical expression is evaluated first. If this value is true, the statement is executed. Then the value of the expression is checked again, and everything is repeated until the expression evaluates to false. Each execution of the loop is sometimes referred to as a loop iteration. If the expression evaluates to false at the first check, then the statement is not executed at all.

In a loop with a precondition, a preliminary check is determined whether to execute the loop body or not, before the first iteration. If this is consistent with the logic of the algorithm, then a loop with a postcondition can be used.

Loop with postcondition looks like:

Repeat ...<выражние_1>until ...<выражение_2>

Here, the statement statement is executed first, and only then the value of the logical expression is evaluated. That is why such a loop is called a postcondition loop. The process repeats as long as the expression evaluates to false. As soon as its value becomes true, the execution of the loop is terminated. Any operator can be, including a compound operator:

Operator_1;

Operator_2;

…………….

Operator_N;

Until<условие>

In a repeat ... until loop, the check is performed last, and the body of the loop is executed at least once in any case.

Counter loop operators: for ... to ... do and for… downto… do.

The third variant of the loop operator is loop with parameter... It can be considered that there are two very similar types of the counter loop. The first of these operators is:

For loop parameter: = start value to end value do<оператор>;

The statement representing the body of the loop can be simple or compound. The loop parameter, as well as the range of its variation, can only be of integer or enumerated type. The parameter is described together with other variables.

After execution of the for loop, the value of the control variable becomes undefined.

The for… downto ... do ... variant of the for loop is similar to the for..to… do loop, except that in it the control variable is not incremented at each execution step, but decremented by one:

for j: -<выражение_1>downto<выражение_2>do<оператор>.

Summing up, the following recommendations can be formulated for using cycles:

Use a for loop when you know exactly how many times the body of the loop should be executed. Otherwise, refer to repeat or while loops.

· Use while if you want the check to be performed before the loop body is executed.

· Sometimes it is convenient to check for a possible exit from the loop somewhere in its middle, and not at the beginning or end.

This breakout of the loop is provided by the Break procedure, which interrupts the execution of the innermost nested loop, be it for, while, or repeat. The specified module is connected to the program automatically, if necessary.

While true do begin

<Выражение_1>

If<оператор>then Break

<Выражение_2>; end

We should also mention the Continue procedure, which interrupts the execution of the body of the innermost for, while, or repeat loop and transfers control to its head, so that the next iteration of the loop begins.

The step of the for loop is always constant and is equal to the interval between the two nearest values ​​of the type of the loop parameter.

Var (description of cycle parameters)

i: integer (integer type);

c: char (character type);

1. Begin (printing out integers from 1 to 10)

For i: = 1 to 10 do writeln (i); (loop step is 1)

2. (printing numbers from 10 to -10)

For 10 down to -10 (loop step is -1)

3. (printing out Latin characters from A to R)

(the loop parameter changes from A to R in alphabetical order)

For c: = ‘A’ to ‘R’ do writeln (c);

The cycle starts by assigning a start value to the parameter. This is followed by a check to see if the parameter is greater than the final value. If the result of the check is affirmative, then the cycle is considered complete and control is transferred to the operator following the cycle body. Otherwise, the body of the loop is executed and the parameter changes its value to the next one according to the heading of the loop. Next, the value of the loop parameter is checked again, and the algorithm is repeated.

Example: Calculating the sum from 1 to n.

var s, n, i: integer;

writeln (‘Enter n’);

for i: = 1 to n do s: = s + i;

A function in programming is a separate piece of code that can be called by referring to it by the name that it was named with. When called, the commands of the function body are executed.

Functions can be compared to small programs that by themselves, that is, autonomously, are not executed, but are embedded in a regular program. Often they are called subroutines. There are no other key differences between functions and programs. Functions can also receive and return data as needed. Only they usually get them not from input (keyboard, file, etc.), but from the calling program. This is where they return the result of their work.

There are many functions built into the programming language. We have already encountered some of these in Python. These are print (), input (), int (), float (), str (), type (). The code of their body is not visible to us, it is somewhere "hidden inside the language". We are only provided with the interface - the name of the function.

On the other hand, the programmer can always define his own functions. They are called custom. In this case, the "user" is understood as a programmer, not the one who uses the program. Let's figure out why we need these functions, and how to create them.

Suppose you need to ask for a pair of numbers for input three times in a row and add them. For this purpose, you can use a loop:

i = 0 while i< 3 : a = int (input () ) b = int (input () ) print (a+b) i += 1

However, what if, before each request for numbers, you need to display an inscription, why are they needed, and each time this inscription is different. We cannot interrupt a loop and then revert back to the same loop. You will have to abandon it, and then you get a long code containing the same sections in different places:

print () a = int (input ()) b = int (input ()) print ("Total", a + b, "pcs.") print () a = int (input ()) b = int (input ()) print ("Total", a + b, "pcs.")

An example of program execution:

How many bananas and pineapples are there for monkeys? 15 5 Total 20 pcs. How many beetles and worms are there for hedgehogs? 50 12 Total 62 pcs. How many fish and shellfish are there for otters? 16 8 Total 24 pcs.

Function injection allows you to solve the problem of code duplication in different places in the program. Thanks to them, you can execute the same piece of code not immediately, but only when you need it.

Function definition. Def statement

In the Python programming language, functions are defined using the def statement. Consider the code:

def countFood (): a = int (input ()) b = int (input ()) print ("Total", a + b, "pcs.")

This is an example of a function definition. Like other complex instructions like conditional operator and for looping a function consists of a header and a body. The header ends with a colon and a newline. The body is indented.

The def keyword tells the interpreter that there is a function definition in front of it. The def is followed by the name of the function. It can be anything, as well as any identifier, for example, a variable. In programming, it is highly desirable to give everything meaningful names. So in this case, the function is called "count food" in translation into Russian.

Parentheses are placed after the function name. In the example shown, they are empty. This means that the function does not accept any data from the calling program. However, it could accept them, and then the so-called parameters would be indicated in brackets.

The colon is followed by a body containing the instructions that are executed when the function is called. A distinction should be made between the definition of a function and its call. V program code they are not close and not together. You can define a function, but never call it. You cannot call a function that has not been defined. By defining a function, but never calling it, you never execute its body.

Function call

Consider full version programs with function:

def countFood (): a = int (input ()) b = int (input ()) print ("Total", a + b, "pcs.") print ( "How many bananas and pineapples are there for the monkeys?") countFood () print ( "How many beetles and worms are there for hedgehogs?") countFood () print ( "How many fish and shellfish are there for otters?") countFood ()

After each informational message is displayed on the screen, the function is called, which looks simply like a mention of its name with brackets. Since we do not pass anything to the function, the parentheses are again empty. In the above code, the function is called three times.

When a function is called, the program flow goes to its definition and starts executing its body. After the body of the function is executed, the flow of execution returns to the main code at the place where the function was called. Next, the expression following the call is executed.

In Python, the definition of a function must precede its calls. This is due to the fact that the interpreter reads the code line by line and does not yet know what is downstream. Therefore, if the function call precedes its definition, then an error occurs (a NameError exception is thrown):

print ( "How many bananas and pineapples are there for the monkeys?") countFood () print ( "How many beetles and worms are there for hedgehogs?") countFood () print ( "How many fish and shellfish are there for otters?") countFood () def countFood (): a = int (input ()) b = int (input ()) print ("Total", a + b, "pcs.")

Result:

How many bananas and pineapples are there for monkeys? Traceback (most recent call last): File "test.py", line 2, in< module>countFood () NameError: name "countFood" is not defined

For many compiled languages, this is not required. There you can define and call a function in arbitrary places in the program. However, for readability of the code, programmers prefer to follow certain rules even in this case.

Functions give structure to a program

The use of functions is not only in the ability to repeatedly call the same code from different places in the program. It is equally important that they give the program its true structure. Functions, as it were, divide it into separate parts, each of which performs its own specific task.

Suppose you need to write a program that calculates the areas of different shapes. The user specifies the area of ​​which figure he wants to calculate. After that, he enters the initial data. For example, the length and width in the case of a rectangle. To split the flow of execution into multiple branches, use the if-elif-else statement:

figure = input () if figure == "1": a = float (input ("Width:")) b = float (input ("Height:")) print ("Area:% .2f"% (a * b)) elif figure == "2": a = float (input ("Base:")) h = float (input ("Height:")) print ("Area:% .2f"% (0.5 * a * h)) elif figure == "3": r = float (input ("Radius:")) print ("Area:% .2f"% (3.14 * r ** 2)) else: print ("Input error" )

There are no functions here and everything is fine. But let's write a variant with functions:

def rectangle (): a = float (input ("Width:")) b = float (input ("Height:")) print ("Area:% .2f"% (a * b)) def triangle (): a = float (input ("Base:")) h = float (input ("Height:")) print ("Area:% .2f"% (0.5 * a * h)) def circle (): r = float (input ("Radius:")) print ("Area:% .2f"% (3.14 * r ** 2)) figure = input ( "1-rectangle, 2-triangle, 3-circle:") if figure == "1": rectangle () elif figure == "2": triangle () elif figure == "3": circle () else: print ("Input error")

It seems more complicated, and each of the three functions is called only once. However, from the general logic of the program, instructions for finding areas have been removed and isolated. The program now consists of separate "Lego bricks". In the main branch, we can combine them as we like. It plays the role of a control mechanism.

If we ever want to calculate the area of ​​a triangle using Heron's formula, and not in terms of height, then we don't have to search for code in the entire program (imagine that it consists of thousands of lines of code like real programs). We will go to the place where the functions are defined and change the body of one of them.

If you need to use these functions in some other program, then we can import them there, referring to this file with code (as it is done in Python, will be discussed later).

Practical work

In programming, you can call another from one function. To illustrate this possibility, write a program according to the following description.

The main branch of the program, not counting the function headers, consists of one line of code. This is a call to the test () function. It asks for an integer to be entered. If it is positive, then the positive () function is called, the body of which contains the command to display the word "Positive" on the screen. If the number is negative, then the negative () function is called, its body contains the expression for displaying the word "Negative".

Local and global variables

The basis of any computer program- algorithms expressed as commands. Human, writing code, indicates, they say, take this, do this, this and that to him, and then bring the result over there and go to rest. So that the commands in the programs do not merge into a single mess and can interact with each other, they are grouped into so-called functions and procedures. We will get acquainted with these concepts.

What is a function

Function names are used: 1) to create documentation; 2) for an API, that is, an interface for connecting to a program or an entire operating system of any applications. Therefore, it makes sense to remind once again that these names should be given intelligible and, if possible, appropriate to the actions performed.

Let's summarize

So, functions are a kind of containers for grouping algorithms. They:

  1. are responsible for specific tasks;
  2. interact with other objects;
  3. are the conceptual framework modern programming, no matter how pretentious this may sound.

Procedures are actually the same functions, albeit "empty", returning nothing (this is their main difference). A kind of auxiliary tools designed to perform routine activities, as well as to save space, effort and time.

Previous publications:

By definition, it is an independent unit of the program, designed for the implementation of a specific task. To put it simply, a function is a bunch of several operators, allocated in a separate block. The function is subject to all the rules and standards of the C language.

Positive points:

A function can be called for execution at any time and anywhere in the program, and more than once;

Functions save the programmer from routine cloning of a lot of repetitive operators;

The same function can be inserted into completely different programs, thereby reducing development and debugging time;

The use of functions increases the modularity of the program, its structuredness, which makes it easier to read the listing, speeds up the introduction of changes.

What do you need to know about functions? Firstly, how to call them correctly from the program, secondly, how to arrange them into separate libraries, and thirdly, how to establish relationships with other functions.

Functions in the C language can be conditionally divided into three types: system, internal and external.

System functions come with any compiler. In WinAVR they can be found in the library reference located at C: \ WinAVR-2010010 \ doc \ avr-libc \ avr-libc-user-manual.pdf (hereinafter referred to as the "Library Manual").

Each system function is strictly included in its own library. The names of libraries and functions are different in different compilers. The declaration of the libraries used is made in the "header" of the program by the preprocessor directive "# inC1ude<имя заголовочного файла-хеддера>».

The "#" symbol is written together with the word "inC1ude" and necessarily begins in the first column of the listing. "Headder" is a file with the ".h" extension, which describes the parameters of functions. The head function "main" also belongs to the system functions, without which no C program can do.

Strictly speaking, the use of system functions makes it difficult to port programs from one MK platform to another. Different compilers have different programming philosophy. For example, some developers try to include in the compiler only internationally standardized libraries and functions, while others, on the contrary, create many of their highly specialized functions that are very convenient for programmers, but absolutely far from standards.

The AVR-GCC compiler used in the WinAVR package occupies a golden mean in comparison with other compilers. In its composition there are approximately equal parts of the functions of the generally accepted standards ANSI, C99, as well as its own microcontroller libraries.

Having thoroughly studied the system functions of one compiler, the programmer to some extent "becomes attached" to them and does not want to relearn new ones. This is where a truly chess calculation is required in order to choose a solid, powerful and constantly updated (which means, "live"!) Compiler for study from the first time. By the way, AVR-GCC still meets all user expectations.

The standard compiler libraries, along with functions, also include system macros, for example, specific to the WinAVR package "_BV", "bit_is_set", "bit_is_C1ear". Details of their use are covered in the Library Guide.

Internal functions are created by the programmer himself. Their number in the program is limited only by the developer's imagination. Internal functions, as a rule, are added at the end or at the beginning of the general listing and can be called both from the main program and from other functions. A special position is occupied by interrupt handlers, which semantically also refer to internal functions, although they have a special description system.

How many times should the inner function be called? It is desirable two or more times, otherwise the benefits from its use are lost. Using internal functions is effective where you need to perform the same repetitive actions over and over again. The more often the functions are called, the higher the compression ratio of the program code is obtained.

External functions, by definition, are outside the main listing, namely, in a separate file. They are structurally similar to internal functions. But why, then, are they singled out as a separate group? There are several reasons.

1. Compilers have physical limits on the length of the processed files. For example, if when compiling one large listing, the error message "Ergog" appears, then you can select some of the internal functions in a separate file (make them external) and everything will go fine.

2. Programs with a large number of lines are more difficult to analyze, correct, and debug. In order to observe the principle of modularity, it is advisable to split the program into logically separate small parts that can be easily edited, rearranged, and replaced.

3. If we make external functions as autonomous as possible, then in the future they can be used in conjunction with other programs. Forward-thinking programmers try to create their own "native" libraries, consisting of specialized functions. For example, Pascal Stang's free library contains a good set of ready-made external functions for AVR controllers.

According to the established tradition, all function names, as well as variable names, are written in small Latin letters. Digits are allowed in all positions of the name, except for the first one on the left. The names of system functions cannot be changed, they are determined by standards, in contrast to internal and external functions, the names of which come up with whoever wants. The only restriction is that the new names differ from the names of the system functions, otherwise the compiler generates an error message: "Error previous definition".

The name of the function must be followed by parentheses, in which, if necessary, indicate the transmitted / received parameters. Table. 6.9 lists all valid declaration and function call formats in AVR-GCC.

Table 6.9. Formats for declaring and calling functions in AVR-GCC

Function declaration format __ "example ()"

A separate system (subsystem, subroutine), to the input of which control actions are received in the form of argument values. At the output, the function returns a result, which can be either a scalar value or a vector value (structure, index array, etc.). During the execution of the function, some changes in the controlled system can also be performed, both reversible and irreversible.

By-effect

Functions and procedures

In some programming languages ​​(for example, in Pascal), functions and procedures (subroutines that do not return values) are clearly delineated by the syntax of the language. In others - for example, in the C language - procedures are a special case (subset) of functions that return a value of type (pseudo-type) void - an empty value.

Arguments and parameters

When a function is called, arguments are passed to it. If the argument is a reference to a memory area (variable, pointer or reference), then the function, depending on the type of its parameter, can either use its value (for example, create a variable, copy the value of the argument there), or the argument itself (create a reference to the area memory referenced by the argument).

Function with no arguments

This function does not require any arguments.

see also

Links

  • PHP functions. PHP function syntax and examples

Wikimedia Foundation. 2010.

See what "Function (programming)" is in other dictionaries:

    The Wiktionary has an article "function" Function is a polysemantic term that means a relationship between elements in which a change in one entails a change ... Wikipedia

    A stub function in programming is a function that does not perform any meaningful action, returning an empty result or input data unchanged. The similar English word is stub. Used: For clarity when ... ... Wikipedia

    higher mental function: recovery- (restoration of higher mental functions) a section of neuropsychology devoted to the study of mechanisms and methods of restoration of higher mental functions, impaired as a result of lesions of the local brain of the brain. Based on ideas about ... ... Big psychological encyclopedia

    Mathematical programming is a mathematical discipline that studies the theory and methods of solving problems of finding extrema of functions on sets of a finite-dimensional vector space, determined by linear and nonlinear constraints ... ... Wikipedia

    In the field of computerization, the concept of programming network tasks, or otherwise called network programming, is quite similar to the concepts of socket programming and client-server programming, ... ... Wikipedia

    Higher-order function A function that takes other functions as arguments or returns another function as a result. The basic idea is that functions have the same status as other data objects. ... ... Wikipedia

    PROGRAMMING MATHEMATICAL- complex mathematical. models and methods for solving problems of finding the extremum (maximum or minimum) of functions of several variables under constraints in the form of inequalities. It means that the variables characterize any aspects of the mechanism ... ... Russian Sociological Encyclopedia

    Mathematical discipline that studies mathematics. abstraction of programs, interpreted as objects, expressed in a formal language, possessing a certain informational and logical. structure and to be executed automatically. devices. P. t. ... ... Encyclopedia of mathematics

    A function in programming is one of the types of subroutines. The peculiarity that distinguishes it from other kind of subroutines of the procedure is that the function returns a value, and its call can be used in the program as an expression. In terms of ... ... Wikipedia

    PROGRAMMING, MATHEMATICAL- a section of applied mathematics used as a method in economic research. Develops the theory and methods for solving conditional extreme problems, is the main part of the formal apparatus for analyzing various control problems ... Big Dictionary of Economics