Formation of matrices and output of its elements. 2D arrays

Two-dimensional array a data structure that stores a rectangular matrix of the form:

A 11 a 12 a 13 a 14 a 15 ... a 1m a 21 a 22 a 23 a 24 a 25 ... a 2m a 31 a 32 a 33 a 34 a 35 ... a 3m a 41 a 42 a 43 a 44 a 45 ... a 4m a 51 a 52 a 53 a 54 a 55 ... a 5m ... ... ... ... ... ... ... a n1 a n2 a n3 a n4 a n5 ... a nm

  • In the matrix, each element is determined by the row number and the column number, at the intersection of which it is located
  • In Pascal, a two-dimensional array is considered as an array whose elements are linear arrays (an array of arrays). The following two descriptions of two-dimensional arrays are identical var mass: array of array of real; var mass: array of real;
  • A matrix in which the number of rows is equal to the number of columns is called square matrix.
  • To refer to a matrix element, you must use two indices denoting the row number and the column number. for example MyArr1... In this case, the array element (MyArr1) is in the fourth row and fifth column.
  • Everything that has been said about the basic operations with one-dimensional arrays is also true for matrices. When iterating over an array in a loop, variables of integer type act as indices. Traditionally, the identifier “ i “And the column is“ j “.
  • Matrix processing consists in the fact that at first the elements of the first row (column) are considered one by one, then the second, and so on until the last.
  • If the line number of the element is the same as the column number ( i \u003d j), this means that the element lies on main diagonal matrices.
  • If an element lies on the side diagonal, then the indices are related to the number of elements ( n) by the following equality: i + j \u003d n + 1

Description of a two-dimensional array

There are several ways to declare (describe) a two-dimensional array in Pascal.

Array type preliminary description

type matrix \u003d array of integer; (array of integers) var mass: matrix;

Defining a variable as an array without prior declaration of the array type

var mass: array of integer;

Initializing a two-dimensional array

When initializing two-dimensional arrays, each line is enclosed in an extra pair of parentheses:

Const mass: array \u003d ((2,3,1,0), (1,9,1,3), (3,5,7,0));

Input / output of values \u200b\u200bof elements of a two-dimensional array

Very often the values \u200b\u200bof array elements are entered from the keyboard. This way of specifying information is too laborious when working with large arrays. To debug a wide class of algorithms, such input of information should be replaced by random generation of array elements. To do this, use the procedure randomize and function random... When working with two-dimensional arrays, nested loops are used (usually a loop with the parameter for).

Filling an array with random numbers

const n \u003d 5; m \u003d 10; var i, j: integer; matrix: array of integer; begin randomize; for i: \u003d 1 to n do (accessing the rows of an array) for j: \u003d 1 to m do (accessing elementwise columns) matrix: \u003d random (100); (we put in the current element a random number from the interval: 4); writeln (transition to a new line upon exiting the inner loop) end;

Examples of problem solving

Example 1

Formulation of the problem. Given positive integers M and N. Form an M × N integer matrix in which all elements of the J-th column have the value 5 · J (J \u003d 1, ..., N).

Const m \u003d 7; n \u003d 10; var i, j: byte; matrix: array of integer; begin for i: \u003d 1 to m do for j: \u003d 1 to n do matrix: \u003d 5 * j; ... (Output array)

Example 2

Formulation of the problem. Given positive integers M, N and a set of M numbers. Form an M × N matrix, each column containing all numbers from the original set (in the same order).

Const m \u003d 5; n \u003d 7; vector: array of integer \u003d (3, 5, 2, 7, 4); var i, j: byte; matrix: array of integer; begin for j: \u003d 1 to n do (take the j-th column) for i: \u003d 1 to m do (refer to the elements of the j-th column by rows) matrix: \u003d vector [i]; (implementation) ... (Outputting the resulting two-dimensional array)

Homework

  1. Given positive integers M and N. Form an integer matrix of size M × N, in which all elements of the first row have the value 10 · I (I \u003d 1,…, M).
  2. You are given positive integers M, N and a set of N numbers. Form an M × N matrix, each row containing all numbers from the original set (in the same order).
  3. Additionally.You are given positive integers M, N, a number D and a set of M numbers. Form an M × N matrix in which the first column coincides with the original set of numbers, and the elements of each next column are equal to the sum of the corresponding element of the previous column and the number D (as a result, each row of the matrix will contain elements of the arithmetic progression).
  4. Additionally.An M × N matrix is \u200b\u200bgiven. Print its elements located in rows with even numbers (2, 4,…). Display elements line by line, do not use the conditional operator.

A two-dimensional array in Pascal is treated as a one-dimensional array, the element type of which is also an array (an array of arrays). The position of elements in two-dimensional Pascal arrays is described by two indices. They can be represented as a rectangular table or matrix.

Consider a two-dimensional Pascal array with dimensions 3 * 3, that is, it will have three lines, and each line has three elements:

Each element has its own number, like in one-dimensional arrays, but now the number already consists of two numbers - the number of the line in which the element is located, and the column number. Thus, the element number is determined by the intersection of the row and column. For example, a 21 is the item in the second row and first column.

Description of a two-dimensional Pascal array.

There are several ways to declare a two-dimensional Pascal array.

We already know how to describe one-dimensional arrays, the elements of which can be of any type, and, therefore, the elements themselves can be arrays. Consider the following description of types and variables:

An example of describing a two-dimensional Pascal array

Type
Vector \u003d array of<тип_элементов>;
Matrix \u003d array of vector;
Var m: matrix;

We have declared a two-dimensional Pascal array m, consisting of 10 rows, each with 5 columns. In this case, each i-th line can be accessed m [i], and each j -th element inside the i-th line - m [i, j].

Type definitions for two-dimensional Pascal arrays can be specified in one line:

Type
Matrix \u003d array of array of< тип элементов >;
or even simpler:
type
matrix \u003d array of<тип элементов>;

The reference to the elements of a two-dimensional array looks like: M [i, j]. This means that we want to get the item located in the i-th row and j-th column. The main thing here is not to confuse rows with columns, otherwise we can again get a call to a nonexistent element. For example, a call to element M has the correct notation, but it can cause an error in the program.

Basic operations with two-dimensional Pascal arrays

Everything that has been said about the basic operations with one-dimensional arrays is also true for matrices. The only action that can be performed on matrices of the same type as a whole is assignment. That is, if our program describes two matrices of the same type, for example,

type
matrix \u003d array of integer;
var
a, b: matrix;

then during program execution you can assign to the matrix a matrix value b (a: \u003d b). All other actions are performed element by element, while on the elements you can perform all the allowed operations that are defined for the data type of the array elements. This means that if an array consists of integers, then operations defined for integers can be performed on its elements, but if the array consists of characters, then operations defined for working with characters are applicable to them.

Input of a two-dimensional Pascal array.

To sequentially enter the elements of a one-dimensional array, we used a for loop, in which we changed the index value from the 1st to the last. But the position of an element in a two-dimensional Pascal array is determined by two indices: the row number and the column number. This means that we will need to sequentially change the row number from the 1st to the last, and in each row, iterate over the elements of the columns from the 1st to the last. This means that we need two for loops, and one of them will be nested within the other.

Consider an example of entering a two-dimensional Pascal array from the keyboard:

An example of a program for entering a two-dimensional Pascal array from the keyboard

type
matrix \u003d array of integer;
var
a,: matrix;
i, j: integer; (array indices)
begin
for i: \u003d 1 to 5 do (loop to iterate over all lines)
readln (a [i, j]); (keyboard input of the element in the i-th row and j-th column)

A two-dimensional Pascal array can be filled randomly, i.e. use the random (N) function, and also assign the value of some expression to each element of the matrix. The way to fill the two-dimensional Pascal array is chosen depending on the task at hand, but in any case, each element in each row and each column must be defined.

Displays a two-dimensional Pascal array on the screen.

The elements of a two-dimensional Pascal array are also output sequentially; it is necessary to print the elements of each row and each column. At the same time, I would like the elements on the same line to be printed side by side, i.e. into a row, and the elements of the column were located one below the other. To do this, you need to perform the following sequence of actions (consider the program fragment for the array described in the previous example):

An example of a program for outputting a two-dimensional Pascal array

for i: \u003d 1 to 5 do (loop to iterate over all lines)
begin
for j: \u003d 1 to 10 do (iterate over all elements of the row by column)
write (a [i, j]: 4); (printing the elements located in the i-th row of the matrix in one screen line, while 4 positions are allocated for the output of each element)
writeln; (before changing the row number in the matrix, you need to move the cursor to the beginning of a new screen line)
end;

Remark ( it is important!): very often in student programs an error occurs when keyboard input or array output is attempted as follows: readln (a), writeln (a), where a Is an array variable. However, they are surprised by the compiler's message that a variable of this type cannot be read or printed. Maybe you will understand why this cannot be done if you imagine N mugs standing in a row, and you have, for example, a kettle of water in your hands. Can you fill all the mugs at once on the command "pour water"? No matter how hard you try, you will have to pour into each mug separately. Filling and displaying array elements should also be carried out sequentially and element by element, since in the computer memory, the array elements are located in sequential cells.

A two-dimensional Pascal array representation in memory

The elements of an abstract array in the machine memory are physically located sequentially, according to the description. Moreover, each element occupies in memory the number of bytes corresponding to its size. For example, if the array consists of elements of type integer, then each element will take two bytes. And the entire array will take S ^ 2 bytes, where S is the number of elements in the array.

And how much space will an array consisting of arrays take, i.e. matrix? Obviously: S i ^ S j, where S i is the number of lines, and S j is the number of elements in each line. For example, for an array like

Matrix \u003d array of integer;

it will take 12 bytes of memory.

How will the elements of this array be located in memory? Consider the layout of an array M of type matrix in memory.

Two memory cells are allocated for each element M of type integer. Placement in memory is carried out "from the bottom up". The elements are placed in the order of index change, which corresponds to the scheme of nested loops: first the first line is placed, then the second, the third ... Inside the line, the elements go in order: first, second, etc.

As we know, access to any variable is possible only if the address of the memory cell in which the variable is stored is known. A specific memory is allocated for a variable when the program is loaded, that is, a mutual correspondence is established between the variable and the cell address. But if we declared the variable as an array, then the program "knows" the address of the beginning of the array, that is, its first element. How do you access all other elements of the array? With real access to a memory cell in which an element of a two-dimensional array is stored, the system calculates its address using the formula:

Addr + SizeElem * Cols * (I -1) + SizeElem * (J -1),

where Addr is the actual starting address at which the array is located in memory; I, J - element indices in a two-dimensional array; SizeElem - the size of the array element (for example, two bytes for integer elements); Cols - the number of elements in the line.

The expression SizeElem * Cols * (I -1) + SizeElem * (J -1) is called the offset from the beginning of the array.

How much memory is allocated for the array?

Let's consider not so much the question of how much memory is allocated for the array (we discussed this in the previous section), but what is the maximum allowable size of the array, given the limited amount of memory.

For the program to work, memory is allocated in segments of 64 KB each, and at least one of them is defined as data segment... It is in this segment that the data that the program will process is located. No program variable can be located in more than one segment. Therefore, even if there is only one variable described as an array in the segment, then it cannot receive more than 65536 bytes. But almost certainly, in addition to the array, some more variables will be described in the data segment, so the real amount of memory that can be allocated for the array is found by the formula: 65536-S, where S is the amount of memory already allocated for other variables.

Why do we need to know this? In order not to be surprised, if, during compilation, the translator generates an error message about declaring an array that is too long when it encounters a description in the program (correct in terms of syntax):

Type myArray \u003d array of integer;

You already know that, given the two-byte representation of integers, you can actually declare an array with the number of elements equal to 65536/2 –1 \u003d 32767. And then only if there are no other variables. Two-dimensional arrays should have even smaller index bounds.

Examples of solving problems with two-dimensional Pascal arrays

A task: Find the product of nonzero elements of the matrix.

Decision:

  • To solve this problem, we need variables: a matrix consisting, for example, of integer elements; P is the product of elements other than 0; I, J - array indices; N, M - the number of rows and columns in the matrix.
  • Input data are N, M - enter their values \u200b\u200bfrom the keyboard; matrix - we will arrange the input of the matrix in the form of a procedure; using the random () function.
  • The output will be the value of the variable P (product).
  • To check the correctness of the program execution, it is necessary to display the matrix on the screen, for this we will issue the procedure for displaying the matrix.
  • Progress in solving the problem:

we will first discuss the execution of the main program, we will discuss the implementation of the procedures a little later:

  • enter the values \u200b\u200bof N and M;
  • Let's introduce a two-dimensional Pascal array, for this we turn to the procedure vvod (a), where a is a matrix;
  • Let's print the resulting matrix, for this we refer to the print (a) procedure;
  • Let's assign the initial value to the variable P \u003d 1;
  • We will sequentially iterate over all rows of I from the 1st to the Nth, in each row we will iterate through all the columns of J from the 1st to the Mth, for each matrix element we will check the condition: if a ij? 0, then the product P will be multiplied by the element a ij (P \u003d P * a ij);
  • Let's display the value of the product of nonzero matrix elements - P;

Now let's talk about the procedures.

Comment (it is important!) A procedure parameter can be any variable of a predefined type, which means that to pass an array as a parameter to the procedure, its type must be described in advance. For example:

Type
Matrix \u003d array of integer;
procedure primer (a: matrix);
..............................

Let's get back to our procedures now.

The procedure for entering a matrix is \u200b\u200bcalled vvod, the parameter of the procedure is a matrix, and it must be passed as a result to the main program, therefore, the parameter must be passed by reference. Then the header of our procedure will look like this:

Procedure vvod (var m: matrix);

To implement nested loops in a procedure, we need local counter variables, for example, k and h. The matrix filling algorithm has already been discussed, so we will not repeat it.

The procedure for displaying a matrix on the screen is called print, the parameter of the procedure is a matrix, but in this case it is an input parameter, therefore, it is passed by value. The title of this procedure will look like this:

Procedure print (m: matrix);

And again, to implement nested loops within a procedure, we need counters, let them be called the same - k and h. The algorithm for displaying the matrix on the screen was described above, we will use this description.

An example of a two-dimensional Pascal array program

Program proizvedenie;
Type
Matrix \u003d array of integer;
Var
A: matrix;
N, m, i, j: byte;
P: integer;
Procedure vvod (var m: matrix);
Var k, h: byte;
Begin
For i: \u003d 1 to n do (variable n for the procedure is global, which means "known")
For j: \u003d 1 to m do (the m variable for the procedure is global, which means "known")
M: \u003d random (10);
End;
Procedure print (m: matrix);
Var k, h: byte;
Begin
For i: \u003d 1 to n do
begin
For j: \u003d 1 to m do
Write (M: 4);
Writeln;
end;
End;
Begin (the beginning of the main program)
Writeln ("Enter the dimension of the matrix:");
Readln (N, M);
Vvod (a);
Print (a);
P: \u003d 1;
For i: \u003d 1 to N do
For j: \u003d 1 to M do
If a<>0 then p: \u003d p * a;
Writeln (p);
End.

The last lesson Pascal was written as early as March 7, then we analyzed. Today we will find out what it is two dimensional array in pascal, how it is described and what it is. More details below.

So what exactly is a two-dimensional array?For easy perception, we represent a one-dimensional array as a line, and in which all the elements go horizontally one after another, and a two-dimensional one as a square, in which the elements are located both horizontally and vertically. A two-dimensional array consists of rows and columns, also called a matrix or matrix array.

How are two-dimensional arrays described? There are several ways to write two-dimensional arrays, I will consider 2 of them.

1 way to describe an array: array of type of variables in the array (integer / real / byte);

2 way to describe an array: array of array of type of variables in the array;

Rows (1..m) are described first, and then columns (1..n).

The second method describes, as it were, two one-dimensional arrays, which together form one two-dimensional.

A two-dimensional array can be described in the Type section, for subsequent reference to it several times, or in the variable description section Var, I want to note that instead of m and n, you can substitute numbers, or you can use constants.

An example of setting a two-dimensional array in the variable declaration section:

Const
m \u003d 100;
n \u003d 100;
var
a: Array of integer;

In this case, we specified a two-dimensional array a of 100 by 100 size, that is, we got a square matrix.

An example of defining a matrix array using the Type section:

Const
m \u003d 100;
n \u003d 100;
Type
Matrix \u003d Array of integer;
var
a: Matrix;
b: Matrix;

In the second example, we specified two identical matrix arrays with dimensions of 100 by 100, while describing the b array, we did not have to describe its sizes and data type again.

How do I access a variable cell of a two-dimensional array?

To refer to a two-dimensional array, you must first specify the row number and then the column number as follows:

x is any variable, a is the name of the array, i is the row number, j is the column number.

Moreover, i and j can be both variables and integers.

An example of writing data to an array:

For i: \u003d 1 to n do // set the line number in the loop
For j: \u003d 1 to m do // assigning the column number in the loop
a: \u003d random (100); // assigning a random value to the cell with row number i and column number j

We filled the array with random numbers from 1 to 100.

An example program using a two-dimensional array, in which we fill the array with random numbers and display it on the screen:

Var // description of variables and array
Matrix: Array of integer;
i, j: integer;

Begin // start of the main program
writeln ("Two-dimensional array:"); // Dialogue with the user

For i: \u003d 1 to 10 do // filling the array
for j: \u003d 1 to 10 do
Matrix: \u003d random (100);

For i: \u003d 1 to 10 do begin // Output the array
for j: \u003d 1 to 10 do
write (matrix, "");
writeln
writeln ("site"); // Optionally, you can delete
end; // End of program

// readln // Used in Turbo Pascal