Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Write down and run this program on your computer

Programs and algorithms | Algorithms and programming languages | Fundamentals of programming I | Student is obliged to write down and run this program by himself | Data in a program (variables and literals) | Operations on data (operators and expressions) | Fundamentals of programming II | The first program | Types. Primitive types. | Types of variables. Declarations. |


Читайте также:
  1. A FIRST LOOK AT COMPUTERS
  2. A friend of yours wants to develop a programme to protect the city where he lives. Give him a piece of advice.
  3. A writer’s life
  4. A writer’s life
  5. A) write a letter to Peter;
  6. Active Directory Users and Computers
  7. Algorithms and programming languages


It is possible to use multidimensional arrays. In our simplified REXX such arrays are accessed in the following way:

a[i][j][k]...

where consecutive pairs of square brackets are used to index corresponding dimension.

Typical example of a two-dimensional array is a matrix (a table of numbers organized in rows and columns).
The next program multiplies square matrices. The element in row i and column j of matrix C, which is the product of matrices A and B, is the sum of products of elements in row i of the A matrix by elements in column j of the B matrix.

/* Multiplication of square matrices */ N = 2; a[1][1] = 1; b[1][1] = 2;a[1][2] = 2; b[1][2] = 2;a[2][1] = 3; b[2][1] = 3;a[2][2] = 7; b[2][2] = 2; do i = 1 to N; do j = 1 to N; c[i][j] = 0; do k = 1 to N; c[i][j] = c[i][j] + a[i][k] * b[k][j]; end endend say 'Result:'do i = 1 to N out = '' do j = 1 to N out = out right(c[i][j], 8) end say outend

Result:
8 6
27 20

The result is given by rows, appending elements of each row to the variable out. The function right() puts its first argument (c[i][j] in this case) into a field of size determined by the second argument (8) with justification to the right. Thanks to this function we get pretty-printed output

 

Functions

The idea of dividing a program into parts which - incorporated into a program once - can be used repeatedly is (in one way or another) realized in probably all programming languages.
Such separated parts are called subprograms, subroutines, procedures or functions.
The differences between these notions are rather vague. Sometimes it is said, that a function is a procedure (subroutine) which produces some value as a result of its execution.
The C and C++ languages use the notion of function exclusively to call both kinds of procedures.
In object oriented languages other than C++ (in that case Java), as the equivalent of the notion of function, the notion of method is used. The difference between "function" and "method" will be explained by the presentation of object oriented programming fundamentals.

A function is a separate set of instructions included in a program which can be linked with the program once (by means of inclusion or during compilation or interpretation), but can be invoked (used) repeatedly from various parts of the program.

 

To define a function the following must be determined:

Each programming language has its own syntax specifying function signature and marking off its body.

Note: in the original REXX we use the notion of procedure, and the syntax is quite different.

In our simplified REXX the function signature is designated with the word function put at the beginning of the line and followed by the function name and list of parameters enclosed in parentheses (specifying the information delivered to the function). The function body (following the header) is terminated with the return statement, which passes control to the place in code where the invocation of this function occurred (possibly returning the result of the function as the value of the expression following the word return).


function function_name (parameter_list)
ins1
ins2
...
insN
return [ expression ]

Note:

 

But what is the list of parameters?

Parameters are variables used to pass information to function body.

 

Thus, to understand the notion of a function we have to know how it is called from a program.

The call (invocation) of a function is an expression of the following form:

function_name(parameter_list)

 


For example, we define a function which compares two values. To each invocation of this function two arguments are passed: the values to compare. Inside the function body they are accessible by means of the corresponding parameter names. After the comparison is done, its result is returned to the place of invocation (0 - values are different, 1 - the first argument is greater than the second one, -1 - the first is less than the second one).

The function name: compare
The parameters: val1, val2
The first invocation uses arguments a and b. Their values are passed to the function and are stored in the parameters val1 and val2 respectively.
The function body states, that val1 (i.e. the value of the variable a) is less than val2 (i.e. the value of the variable b) and according to this the value of the variable r is set. This value is then returned to the place of invocation by means of return statement. The assignment instruction stores it into the variable wynik.

Note, that this function:

Creating a function we have to know not only how to formulate its definition, but also where to place it in the structure of the whole program. Again, different languages apply different rules here.
In our simplified REXX we differentiate the main program and other functions.
The main program starts in the first line of the source file and ends with the exit statement (which specifies the end of the program execution). Definitions of functions are placed behind.

Functions may have no parameters.

Even if a function has no parameters, it is still required to put parentheses after its name in the function definition.
Invoking any function without specifying arguments, the empty parentheses must be appended to the function name.

 

Now the invocations of functions linein(), time(), right() (used earlier in the examples) should be clear. Some useful functions are made available as so called built-in (into REXX) functions. Other languages use so called libraries of standard functions which are ready to use. The Java packages (although they have a bit different properties) are similar to standard libraries of functions.

The built-in or standard functions are precompiled, ready-to-use-in-programs functions which carry out many useful tasks: string processing, mathematical operations, input-output.

 

By the definition of a variable in REXX we mean the first assignment of a value to this variable. Some other programming languages differentiate the declaration of a variable from its definition. Declarations of variables will be discussed later.

Creating and using functions we have to consider the following problems:

Most programming languages treat the variables defined in function body as local variables.

Our simplified REXX deals with local blocks introduced by function definition only. Other languages permit nested blocks (introduced by the grouping instruction) - in C or Java they are created with the help of braces.

The function body is a special case of the so called local block. Indeed, the function definition groups instructions (in REXX between function signature and the return statement inclusive). The modifier local characterizes block's properties: each variable defined in this block is local.

A local variable is a variable defined in a local block, visible(to a compiler or an interpreter, and existing only in that block, from the definition of the variable until the end of the block.

 

Let us consider a simple example:

a = 3;b = 5;func1();func2();say "main a =" a "b =" b;exit; function func1() a = 7; b = 10; c = 12; func2(); say "func1 a =" a "b = " b "c = " c; return; function func2() expose c a = 100; b = 101; c = 101; say "func2 a =" a "b = " b "c = " c; return;

Program's output:
func2 a = 100 b = 101 c = 101
func1 a = 7 b = 10 c = 12
func2 a = 100 b = 101 c = 101
main a = 3 b = 5

Important observations:

It should be clear that the variables a, b, c are local to the functions func1 and func2 (thus they exist only in the given function body). The output of the program confirms that each of the functions operates on its local variables a, b, c. Therefore - in spite of invocation of func2 from func1 - the values of the variables a, b, c at the end of func1 are 7, 10, 12 respectively (not 100, 101, 101). Similarly the variables a and b at the end of the program execution (after the invocation of func1) have values set in the first and second instructions of the main program.

Sometimes however - besides access to the information passed as arguments - a function should have access to variables defined outside of its body.

In the C language such an effect can be obtained with the help of the so called global variables which are declared outside of any function body. In Java the class fields are used for this purpose.

In REXX the mechanism of sharing common variables is quite flexible. For each particular function we can specify in its signature which of the variables (including arrays) defined outside of its body are accessible inside it. The expose statement is used for this purpose.

 

function (parameter_list) expose variables_list

where:

 

The second important problem mentioned earlier concerns the manner of passing arguments by the function invocation.

In general there are two ways of passing arguments to the function: by value and by name.

An argument is passed by value, if by function invocation the value of the argument is stored (copied) to the variable (the parameter) occurring in the list of function parameters in the function definition.

 

It has important consequences. Function parameters are local variables. Therefore - by passing arguments by value - inside the function we have access to the parameter value (by means of variable-parameter). However, changes to this value are valid only to that variable-parameter, not the variable used to pass the argument to the function.

Consider an example:

a = 3;tryChange(a);say a;exit; function tryChange(a) a = a + 1; return;

This function gets as the parameter a - the value of the variable a defined in the first line.
Because of passing by value, the value of the variable a (3) is stored in the local variable - parameter a (accidentally called likewise; however it is different variable). Thus, everything done to the variable a has a local nature and does not concern the variable a from the main program.

Modifications of variables passed by value have no effect (outside the function).

 

 

Because of implementation of arrays in C, C++ and Java, elements of arrays passed to functions may be modified from their bodies (but it does not mean, that arguments are passed by name). In the simplified REXX passing of arrays as arguments is forbidden. Instead the expose clause is used.

Some programming languages permit passing arguments by name (a function gets the argument address instead of its value). With this address given, we can read the variable's value as well as store some new value there. This semantics of argument passing, however, is not possible in Java nor in our simplified REXX, so we will not discuss it.


Let us go back to the problem of calculating a computer price.
In the first lecture various algorithms solving this problem were presented. We paid special attention to the need of data checking (is the given price a number?). In the following program we take this requirement into account. We also want to give a user the possibility of calculating each component's contribution to the final price, as well as modifying the price of a selected component.
We break our problem into subproblems:

The tasks 1-3 are realized as functions (input of the component price - inputData(...), calculation of the computer price - sumPrices(), selection of the component id - choose()). The remaining two tasks, as well as the arrangement of the data and the order of function invocation, are realized by the main program.

Here is the main program:

/* Calculation of the computer price */ /* the array for storing the names of the components */ elt[0] = 6; /* number of components - under position 0 */elt[] = { "CPU", "Motherboard", "Memory", "HDD", "Monitor", "Other" }; price[0] = elt[0] /* the number of prices equals to the number of components */ do i = 1 to price[0] price[i] = inputData (elt[i]); end more = 1; /* do we repeat calculations and modifications? */do while (more = 1) priceOg = sumPrices (); say "The price of the computer is:" priceOg; nrSkl = choose ("Select a component, which share you want to calculate"); if (nrSkl \= '') then do share = price[nrSkl]/priceOg; say elt[nrSkl] "contribution is:" share; end nrSkl = choose("Select a component, which price you want to alter"); if (nrSkl = "") then more = 0; else price[nrSkl] = inputData (elt[nrSkl]); endexit;


Here are the functions:

function inputData(nazwaSkl) say "Give price of the: " nazwaSkl; needData = 1; do while (needData) price = linein() if datatype(price) = "NUM" then needData = 0; end return price; function sumPrices() expose price[] sum = 0; do i = 1 to price[0] /* by convention, price[0] stores the number of elements in the array price */ sum = sum + price[i]; end return sum; function choose(msg) expose elt[] say msg; do i = 1 to elt[0] /* by convention, elt[0] stores the number of elements in the array elt */ say i '-' elt[i]; end do forever say "Input the selected number or press ENTER to cancel:" nr = linein(); if nr = "" then leave; if (nr < 1 | nr > elt[0]) then say "Wrong choice"; else leave; end return nr;

Notes:


Дата добавления: 2015-11-16; просмотров: 64 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Write down and run this program on your computer| Introduction to objects

mybiblioteka.su - 2015-2024 год. (0.02 сек.)