Various ways to fill and output an array. 2D arrays

An array is a data structure presented as a group of cells of the same type, united under one single name. Arrays are used to process large amounts of the same type of data. The name of the array is what pointers are, I'll tell you a little later. A single cell of array data is called an array element. The elements of the array can be data of any type. Arrays can have one or more than one dimension. Depending on the number of dimensions, arrays are divided into one-dimensional arrays, two-dimensional arrays, three-dimensional arrays, and so on up to n-dimensional arrays. One-dimensional and two-dimensional arrays are most often used in programming, so we will only consider these arrays.

One-dimensional arrays in C ++

One-dimensional array - an array with one parameter characterizing the number of elements of the one-dimensional array. In fact, a one-dimensional array is an array that can only have one string, and n-th number columns. The columns in a one-dimensional array are the elements of the array. Figure 1 shows the structure of an integer one-dimensional array a... The size of this array is 16 cells.

Figure 1 - Arrays in C ++

Note that the maximum index of a one-dimensional array a equals 15, but the size of the array is 16 cells, because the numbering of the cells in the array always starts from 0. The cell index is a non-negative integer by which you can refer to each cell in the array and perform any actions on it (cell).

// syntax for declaring a one-dimensional array in C ++: / * data type * / / * name of a one-dimensional array * /; // example of declaring a one-dimensional array shown in Figure 1: int a;

where, int is an integer;

A is the name of the one-dimensional array;
16 - the size of a one-dimensional array, 16 cells.

Always right after the name of the array, there are square brackets, in which the size of a one-dimensional array is set, this is what the array differs from all other variables.

// another way to declare one-dimensional arrays int mas, a;

Two one-dimensional arrays mas and a are declared with sizes 10 and 16, respectively. Moreover, in this method of declaration, all arrays will have the same data type, in our case - int.

// arrays can be initialized when declared: int a = (5, -12, -12, 9, 10, 0, -9, -12, -1, 23, 65, 64, 11, 43, 39, -15 ); // initialize one-dimensional array

Initialization of a one-dimensional array is performed in curly braces after the sign equals, each element of the array is separated from the previous one by a comma.

Int a = (5, -12, -12,9,10,0, -9, -12, -1,23,65,64,11,43,39, -15); // initialize the array without determining its size.

V in this case the compiler will determine the size of the one-dimensional array itself. The size of the array can be omitted only during its initialization; with the usual declaration of an array, it is necessary to indicate the size of the array. We will develop simple program for processing a one-dimensional array.

// array.cpp: defines the entry point for the console application. #include "stdafx.h" #include << "obrabotka massiva" << endl; int array1 = { 5, -12, -12, 9, 10, 0, -9, -12, -1, 23, 65, 64, 11, 43, 39, -15 }; // объявление и инициализация одномерного массива cout << "indeks" << "\t\t" << "element massiva" << endl; // печать заголовков for (int counter = 0; counter < 16; counter++) //начало цикла { //вывод на экран индекса ячейки массива, а затем содержимого этой ячейки, в нашем случае - это целое число cout << "array1[" << counter << "]" << "\t\t" << array1 << endl; } system("pause"); return 0; }

// code Code :: Blocks

// Dev-C ++ code

// array.cpp: defines the entry point for the console application. #include using namespace std; int main (int argc, char * argv) (cout<< "obrabotka massiva" << endl; int array1 = { 5, -12, -12, 9, 10, 0, -9, -12, -1, 23, 65, 64, 11, 43, 39, -15 }; // объявление и инициализация одномерного массива cout << "indeks" << "\t\t" << "element massiva" << endl; // печать заголовков for (int counter = 0; counter < 16; counter++) //начало цикла { //вывод на экран индекса ячейки массива, а затем содержимого этой ячейки, в нашем случае - это целое число cout << "array1[" << counter << "]" << "\t\t" << array1 << endl; } return 0; }

V lines 10 - 11 declared and initialized is an integer one-dimensional array named array1, the size of which is 16 cells, that is, such an array can store 16 numbers. Any processing of an array is feasible only in conjunction with loops. Which loop to choose for processing an array is up to you. But it is best suited for this task. The counter variable counter will be used to refer to the elements of the one-dimensional array array1. The condition for continuation of the for loop contains a strict inequality sign, since there is no sixteenth index in the one-dimensional array array1. And since the numbering of cells starts from zero, the elements in the array are 16. In the body of the for loop, the cout operator prints the elements of a one-dimensional array (see Figure 2).

Obrabotka massiva indeks element massiva array1 5 array1 -12 array1 -12 array1 9 array1 10 array1 0 array1 -9 array1 -12 array1 -1 array1 23 array1 65 array1 64 array1 11 array1 43 array1 39 array1 -15 Press any key to continue. ... ...

Figure 2 - Arrays in C ++

Let's develop another program for processing a one-dimensional array in C ++. The program should sequentially read ten entered numbers from the keyboard. Sum up all entered numbers, display the result.

// array_sum.cpp: defines the entry point for the console application. #include "stdafx.h" #include << "Enter elementi massiva: " << endl; int sum = 0; for (int counter = 0; counter < 10; counter++) // цикл для считывания чисел cin >> << "array1 = {"; for (int counter = 0; counter < 10; counter++) // цикл для вывода элементов массива cout << array1 << " "; // выводим элементы массива на стандартное устройство вывода for (int counter = 0; counter < 10; counter++) // цикл для суммирования чисел массива sum += array1; // суммируем элементы массива cout << "}\nsum = " << sum << endl; system("pause"); return 0; }

// code Code :: Blocks

// Dev-C ++ code

// array_sum.cpp: defines the entry point for the console application. #include using namespace std; int main (int argc, char * argv) (int array1; // declare an integer array cout<< "Enter elementi massiva: " << endl; int sum = 0; for (int counter = 0; counter < 10; counter++) // цикл для считывания чисел cin >> array1; // read the numbers entered from the keyboard cout<< "array1 = {"; for (int counter = 0; counter < 10; counter++) // цикл для вывода элементов массива cout << array1 << " "; // выводим элементы массива на стандартное устройство вывода for (int counter = 0; counter < 10; counter++) // цикл для суммирования чисел массива sum += array1; // суммируем элементы массива cout << "}\nsum = " << sum << endl; return 0; }

Before processing the array, it must be declared, and the size of the one-dimensional array is 10, since this is stipulated by the condition of the problem. In the variable sum, we will accumulate the sum of the elements of a one-dimensional array. The first for loop fills the declared one-dimensional array with the numbers entered from the keyboard, lines 12 - 13... The counter variable counter is used for sequential access to the elements of the one-dimensional array array1, starting from index 0 and up to and including the 9th. The second for loop prints the elements of the array to the screen, lines 15 - 16... The third for loop sequentially reads the elements of the one-dimensional array and sums them up, the sum is accumulated in the variable sum, lines 17 - 18... See the result of the program in Figure 3.

Enter elementi massiva: 0 1 2 3 4 5 6 7 8 9 array1 = (0 1 2 3 4 5 6 7 8 9) sum = 45 Press any key to continue. ... ...

Figure 3 - Arrays in C ++

First, all 10 numbers were entered sequentially, after which a one-dimensional array was displayed, and the sum of the array numbers was printed.

Two-dimensional arrays in C ++

Up to this point, we have considered one-dimensional arrays, which cannot always be limited to. Let's say you need to process some data from a table. There are two characteristics in a table: the number of rows and the number of columns. Also in a two-dimensional array, in addition to the number of array elements, there are characteristics such as the number of rows and the number of columns of a two-dimensional array. That is, visually, a two-dimensional array is an ordinary table, with rows and columns. In fact, a two-dimensional array is a one-dimensional array of one-dimensional arrays. The structure of a two-dimensional array named a, size m by n, is shown below (see Figure 4).

Figure 4 - Arrays in C ++

where, m is the number of lines of a two-dimensional array;
n is the number of columns in a two-dimensional array;
m * n is the number of elements in the array.

// syntax for declaring a two-dimensional array / * data type * / / * array name * /;

In the declaration of a two-dimensional array, as well as in the declaration of a one-dimensional array, the first thing to do is to specify:

  • data type;
  • the name of the array.

After that, in the first square brackets the number of rows of a two-dimensional array is indicated, in the second square brackets - the number of columns of a two-dimensional array. A two-dimensional array visually differs from a one-dimensional array by the second pair of square brackets. Consider an example of declaring a two-dimensional array. Suppose we need to declare a two-dimensional array, with the number of elements equal to 15. In this case, a two-dimensional array can have three rows and five columns, or five rows and three columns.

// example of declaring a two-dimensional array: int a;

  • a - the name of an integer array
  • the number in the first square brackets indicates the number of lines of the two-dimensional array, in this case there are 5;
  • the number in the second square brackets indicates the number of columns in the two-dimensional array, in this case there are 3.

// initialize a two-dimensional array: int a = ((4, 7, 8), (9, 66, -1), (5, -5, 0), (3, -3, 30), (1, 1, one) );

This array has 5 rows, 3 columns. after the assign sign, common curly braces are placed, inside which there are as many pairs of curly braces as there should be lines in a two-dimensional array, and these brackets are separated by commas. In each pair of curly braces, write the elements of a two-dimensional array, separated by commas. All curly braces must have the same number of elements. Since there are five lines in the array, there are also five inner parentheses. The inner brackets contain three elements each, since the number of columns is three. Graphically, our array will look like a two-dimensional table (see Figure 5).

Figure 5 - Arrays in C ++

In each cell of a two-dimensional array a the value is shown, the address of this cell is shown in the lower right corner. The cell address of a two-dimensional array is the array name, row number, and column number.

Let's develop a simple program for processing a two-dimensional array, which is called "Labyrinth". The maze should be built on the basis of a two-dimensional array. We will choose the size of the maze at our discretion.

// array2.cpp: defines the entry point for the console application. #include "stdafx.h" #include < 33; i++) //переключение по строкам { for (int j = 0; j < 20; j++)// переключение по столбцам if (mas[i][j] == 1) { // вывести два раза символ (номер которого 176 в таблице аски) в консоль cout << static_cast(176); cout<< static_cast(176); ) else cout<< " "; // вывести два пробела cout << endl; } system("pause"); return 0; }

// code Code :: Blocks

// Dev-C ++ code

// array2.cpp: defines the entry point for the console application. #include using namespace std; int main (int argc, char * argv) (// 1-conditionally "walls of the labyrinth" // 2- "correct path, exit from the maze" // 0- "false path" int mas = ((1,2,1 , 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,), // initialization of a two-dimensional array (1,2,1,0 , 0,1,0,1,2,2,2,1,1,1,1,0,0,0,0,1,), (1,2,1,1,0,1,0, 1,2,1,2,2,2,2,2,1,0,1,1,0,1,), (1,2,2,2,2,2,2,1,2,1,1 , 1,1,2,1,0,0,1,0,1,), (1,1,1,1,1,1,2,1,2,1,0,0,1,2, 1,1,0,1,0,1,), (1,0,0,1,0,0,2,2,2,1,1,0,0,2,0,0,0,1 , 0,1,), (1,0,1,1,0,1,1,1,1,1,0,0,1,2,1,1,1,1,0,1,), (1.0.0.0.0.0.0.0.0.0.1.1.1.1.2.1.0.0.0.0.1,), (1.1.1, 1,1,1,0,1,1,1,2,2,2,2,2,1,0,1,1,1,1,), (1,1,0,0,0,1.0 , 0,1,1,2,1,1,1,1,0,0,0,0,1,), (1,0,0,1,0,0,0,0,0,1, 2,2,2,2,1,1,1,1,0,1,), (1,1,1,1,1,1,1,1,1,1,1,1,1,2 , 1,0,0,0,0,1,), (1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,0,1, 1,1,1,), (1,2,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,) , (1,2,1,0,0,0,1,2,2,2,1,0,0,0,0,0,1,1,0,1,), (1,2,1 , 1,1,1,1,2,1,2,1,1,1,0,1,0,0,0,0,1,), (1,2,1,2,2,2, 1,2,1,2,2,2,1,1,1,1,1,1,1,1,), (1,2,1,2,1,2,1,2,1.0 , 1,2,2,2,2,2,2,2,2,2,1,), (1,2,1,2,1,2,1 , 2,1,0,1,1,1,1,1,1,1,1,2,1,), (1,2,1,2,1,2,1,2,1,0, 0,0,0,0,0,0,0,0,2,1,), (1,2,1,2,1,2,2,2,1,0,1,1,1,1 , 1,1,0,1,2,1,), (1,2,1,2,1,1,1,1,1,0,0,0,1,0,1,0,0, 1,2,1,), (1,2,1,2,2,1,0,0,1,1,1,0,0,0,1,0,1,1,2,1,) , (1,2,1,1,2,1,1,0,0,0,0,0,1,0,1,0,0,1,2,1,), (1,2,1 , 1,2,1,0,0,1,1,1,1,1,1,1,1,1,1,1,2,1,), (1,2,1,1,2,1, 1,0,1,2,2,2,2,2,2,2,2,2,2,2,1,), (1,2,1,1,2,1,0,0,1,2 , 1,1,1,1,1,1,1,1,1,1,1,), (1,2,1,1,2,1,0,1,1,2,1,1,1, 1,1,1,1,1,2,2,), (1,2,1,1,2,1,0,0,1,2,1,1,2,2,2,2,2,2 , 2,2,1,), (1,2,1,1,2,1,0,1,1,2,1,1,2,1,1,1,1,1,1,1,1, ), (1,2,1,1,2,1,0,0,1,2,1,1,2,1,0,0,0,1,0,1,), (1,2, 2,2,2,1,0,1,1,2,2,2,2,2,0,0,1,0,0,0,1,), (1,1,1,1,1,1 , 1,1,1,1,1,1,1,1,1,1,1,1,1,1,)); // two loops - an internal and an external one, which access each element of the array for (int i = 0; i< 33; i++) //переключение по строкам { for (int j = 0; j < 20; j++)// переключение по столбцам if (mas[i][j] == 1) { // вывести два раза символ (номер которого 176 в таблице аски) в консоль cout << static_cast(176); cout<< static_cast(176); ) else cout<< " "; // вывести два пробела cout << endl; } return 0; }

The correct and false paths could be denoted by the same number, for example, zero, but for clarity, the correct path is denoted by the number 2. The array was initialized manually, just to simplify the program. Since the program is processing a two-dimensional array, two loops are needed to switch between the elements of a two-dimensional array. The first for loop switches between the lines of a two-dimensional array. Since there are 33 strings in a two-dimensional array, the counter variable i is incremented from 0 to 33, line 46... Inside the first loop, there is a for loop that switches between the elements of the string of a two-dimensional array. In the body of the second for loop, a unary data type conversion operation is performed internally - static_cast<>(), which prints character, at number 176. The datatype conversion operation is duplicated to increase the width of the maze. The result of the program (see Figure 6).

Figure 6 - Arrays in C ++

Sections: Informatics

Goals:

  1. To acquaint students with the possibility of filling and processing an array.
  2. Create a graphical interface for a project to fill an array and calculate the sum of elements in a given array.
  3. Develop a cognitive interest in the subject
  4. Foster a responsible learning attitude

DURING THE CLASSES

1. Actualization of the lesson

Organizing time

Frontal poll on the previous topic “The concept of an array. One-dimensional array "

2. Formation of skills and abilities

Explanation of the new material

Array declaration

An array is declared in the same way as a variable is declared, it is only necessary to specify the range of the index change. For example, a one-dimensional integer array containing 10 elements is declared as follows:

A: array of integer;

Basic tasks when working with arrays

1. Formation (filling) of the array

1.1. according to the formulas For i: = 1 to 10 do a [i]: = i * i;

1.2. generate randomly For i: = 1 to 10 do a [i]: = random (20):

Built-in function RANDOM (MAX), returns a random integer evenly spaced from 0 to MAX - 1 (MAX is the call parameter)

1.3. enter from the keyboard For i: = 1 to 10 do read (a [i]);

2. Sorting the array (ascending, descending);

3. Search for elements in an array;

4. Selection of elements from an array by condition;

Filling the array randomly.

To start working with an array, it must be filled, i.e. assign specific values ​​to the elements of the array. To generate a sequence of random numbers, use the Random (100) function. When the program starts, this function will print a pseudo-random sequence of integers in the range from 0 to 100.

To generate sequences of random numbers that differ from each other, it is recommended to use the Randomize operator

Actions with one-dimensional arrays

1. Calculation of the sum of elements

For I: = 1 To 10 Do s: = s + a [i]; (usual accumulation of the sum in s)

2. Calculation of the product

For I: = 1 To 10 Do p: = p * a [i]; (the usual accumulation of the product in p)

3. Search for an element with a given value

3. Note learning skills in practice

The project “Sum of elements in an array”. We will develop a project “Sum of elements in an array”, which will fill the array with random numbers and calculate the sum of these numbers

First, let's create a procedure for filling the array

1. Start the Delphi programming system.

2. Work on the project begins with the creation of a graphical interface, for this in the window Form constructor controls are placed on the form. To create a graphical interface for the project, we will place on the form two text fields for displaying numerical data (one for filling the array, the other for displaying the sum) and two buttons for implementing event procedures: filling the array and the sum

3.Using Toolbars put the Editl text field and the Buttonl command button on the Forml

The next step is to code the event procedures. Double-clicking on the button for which you want to create a program code brings up the window Program code with an empty stub of an event procedure.

4. Double click on the Buttonl button, a template for the event procedure TForml.ButtonlClick will appear: Declare the array A and variable description I, S in the variable declaration section var

A: array of integer;

procedure TForm1.Button1Click (Sender: TObject);

For I: = 1 To 10 Do

A [I]: = Random (10);

Edit1.Text: = Edit1.Text + "" + IntToStr (a [i]);

5. Save Project As

6. Compilation of the project (Project - Compile)

Now let's create a procedure for calculating the sum of the elements in the filled array

Via Toolbars n Place the Button2 button and the Edit2 text field on the Forml form. Double-clicking on Button2, for which you need to create a program code, calls the window Program code with an empty stub of an event procedure.

procedure TForm1.Button2Click (Sender: TObject);

For I: = 1 To 10 Do

Edit2.Text: = Edit2.Text + "" + IntToStr (s)

Saving the project of the entire project (Save Project).

Let's compile the project (by pressing the F9 key).

Click on the Fill Array and Sum buttons.

The results of the amounts will be displayed in the text box for different filling options

4. Summing up

5. Homework: Create a project "Product of array elements", providing for filling the array with random numbers and the ability to display the product of all the elements in the array in the text field.

One-dimensional arrays. Forming an array and displaying its elements

Definition of the concept

An array is a collection of data of the same type with a name common to all elements.

The elements of the array are numbered, and you can refer to each of them by number. The numbers of array elements are otherwise called indices, and the array elements themselves are called indexed variables.

a [n]

- 0. 5

-5.2

0.6

Vector (linear or one-dimensional array) is an example of an array in which elements are numbered with the same index.

  • As numbers (index) array element, in general, the expression is used ordinal type(most often it is an integer constant or an integer variable: integer, word, byte or shortint)
  • When referring to an element of an array, the index is indicated in square brackets. For example, a, mass.
  • Array elements are processed when the element indices change. For example, in the case of using an expression, it is convenient to use the following variables to view array elements in a loop:
    • a [i] - all elements;
    • a - elements in even places;
    • a - elements standing in odd places

Array description

  • Defining a variable as an array without first describing the type of the array
vara, b, c: array of integer; var s: array of integer; k: array of integer;

Note

    • The description of the array is required by the compiler to allocate memory for its elements.
    • A variable is defined as an array by means of a service word array(array). The brackets indicate the range, that is, the lower and upper bounds of the array index value. The upper limit value cannot be less than the lower one.
    • Here the variables s and k are considered to be of different types. To ensure compatibility, it is necessary to apply the declaration of variables through a preliminary type declaration.
    • If the types of the arrays are identical, then in the program one array can be assigned to another. In this case, the values ​​of all variables of one array will be assigned to the corresponding elements of the second array.
    • Relational operations are not defined on arrays. Comparing two arrays can only be element-wise.
  • Array type preliminary description
const n = 5; type mas = array of integer; var a: mas;

Note

    • The elements of the array will be accessed like this: a, a, a, a, a (that is, the array contains five elements).
    • Using constants(n in this example) is preferable when describing an array, since in the case of changing the size of the array, it will not be necessary to make corrections throughout the program text.
  • Specifying an array with a typed constant
const x: array of integer = (1, 2, 3, 4, 5, 6);

Note

    • In this example, not only memory is allocated for the array, but the cells are also filled with data.
    • Array elements can change during the program (like all typed constants).

Filling an array with data

§ To fill the array data (and its output) most often a loop with a parameter is used for

§ To fill the array with random numbers, use the function random and procedure randomize(random number generator initialization). The recording format is as follows: random (B - A) + A, where A and B are taken from the interval: 4);

An example program for input and output of an array

Formulation of the problem. Get the sum of the elements of an array of 10 integer elements. Array elements are entered from the keyboard.

program array2; var sum: integer; i: byte; a: array of word; begin sum: = 0; fori: = 0 to 9 do begin write("a [", i," ] = "); readln(a [i]); sum: = sum + a [i] end; writeln("sum =", sum) end.

An example of a program for working with array elements

Formulation of the problem. Get the arithmetic mean of the elements of an array. The array elements are filled with random numbers.

program array3; const n = 100; var sar: real; sum: integer; i: byte; a: array of integer; begin sum: = 0; randomize; fori: = 0 to n do begin a [i]: = random(one hundred); sum: = sum + a [i] end; sar: = sum / n; writeln("sar =", sar) end.

Lesson from the series: “ Pascal programming language»

After declaring the array, you can work with it. For example, assign values ​​to array elements and generally treat them like ordinary variables. To refer to a specific element, you must specify the identifier (name) of the array and the index of the element in square brackets.

For example, the Mas, A record allows accessing the second element of the MAS array and the tenth element of the A array. When working with a two-dimensional array, specify two indices, with an n-dimensional array - n indices.

For example, the Matr entry makes available for processing the value of the element located in the fourth row of the fourth column of the array M.

Indexed elements of an array are called indexed variables. You cannot go beyond the boundaries of the array. That is, if there are five elements in the Mas array, then access to the sixth or eighth element will result in an error.

Let's consider the typical operations that arise when working with one-dimensional arrays.

Filling a one-dimensional array with values

Filling and displaying an array can be done only element-by-element, that is, you can first assign a value to the first element, then to the second, and so on, the same with displaying - we display the first, second, third and so on until the last.

Pascal does not have means of input-output of array elements at once, therefore input and values ​​are performed element-by-element. An array element can be assigned values ​​using the assignment operator, or entered from the keyboard using the Read or Readln operators. It is very convenient to iterate over all the elements of an array in a for loop.

Ways to fill in one-dimensional arrays:

  1. Entering a value from the keyboard.
  2. Setting values ​​in an assignment statement using a random number generator. This method is more convenient when there are many elements in the array (it takes a lot of time to enter their values ​​from the keyboard).
  3. Setting values ​​by a formula.
  4. Inputting array elements from a file

1. Entering values ​​of array elements from the keyboard. Due to the fact that the Readln statement was used, each value will be entered on a new line.

2. Filling the array numbers generated randomly from the interval. We connect the generator of random numbers - the random function.

3. Filling array according to the formula. Each element in the array is assigned a value calculated by the formula. If each element of the array is equal to three times the value of its ordinal number (index), then the procedure will look like this:

4. Reading numbers from a file. You need to create a text file in advance, in which write down several lines, each of which contains 30 numbers.

Displaying the values ​​of array elements on the screen

Conclusion element values array the screen is executed, like input, element by element in a loop. For output, we will use the Write or Writeln statements. As input parameters, we will pass to the procedure not only an array, but also the number of elements that need to be displayed, starting from the first (we will need this when we delete and add elements in the array).

Example 1. Populate the array from the keyboard and display it.

Solution.

The program will use two procedures: the Init1 procedure (filling the array from the keyboard) and the Print procedure (displaying the array on the screen).

Example 2. Populate the array from a text file and display. The text file contains several lines, each line contains 30 numbers.

You have learned how to fill a one-dimensional array and display it on the screen.

In the next lesson, we will continue to get acquainted with the algorithms for processing one-dimensional arrays.

We can fill the elements of a one-dimensional array with values: by entering values ​​from the keyboard; randomly; according to the formula. Methods for specifying one-dimensional arrays Loops are used to input and output numeric values ​​of an array. The procedure takes a parameter by reference, an Mssiv array of the specified type and an integer variable n responsible for the number of filled array cells. Formation of a one-dimensional array in a random way.


Share your work on social media

If this work did not suit you at the bottom of the page there is a list of similar works. You can also use the search button


Filling.

We can fill the elements of a one-dimensional array with values:

By entering values ​​from the keyboard;

Randomly;

According to the formula.

Methods for defining one-dimensional arrays

Loops are used to input and output numeric array values.

Consider procedures that would form a one-dimensional array in two ways

1) randomly,

2) by entering items from the keyboard

Let's assume we are working with an array of integers. Suppose that it is enough for us to have the maximum number of elements equal to 50. The procedure takes a parameter by reference, a Massiv array of a given type and an integer variable n , which is responsible for the number of filled array cells. We will also need a local variable i , which will act as a loop parameter and be used to specify a number that determines the location of an element in the array.

1. Formation of a one-dimensional array in a random way. Let's set the value of each element with the result of the random function Random (10). Filling the array is set with a cyclic for statement, in the body of which a random number is calculated by the Random (10) function, after which this value is assigned to the next i th element of the array.

Procedure InsertMas1 (Var massiv: mas; n: integer);

I: integer;

Begin

Randomize;

For i: = 1 to n do

Massiv [i]: = Random (10);

End;

2. Formation of a one-dimensional array by entering elements from the keyboard.

Procedure InsertMas2 (Var massiv: mas; n: integer);

I: integer;

Begin

For i: = 1 to n do

Begin

write ("Enter", i , "- th element of the array");

readln (massiv [i]);

End;

End;

The array is displayed on the screen as follows:

Procedure PrintMas (massiv: mas; n: integer);

I: integer;

Begin

For i: = 1 to n

Write (Massiv [i]: 5);

End.

It must be remembered that in all three cases we cannot do without organizing a cycle.

Finding the maximum (minimum) element of an array.

Let's say we have a one-dimensional array:

20,-2, 4, 10,7, 21,-12, 0, 4, 17.

Let's think about what operations need to be performed if we need to find the maximum element. Naturally, the comparison operation We do not think about the fact that we are always comparing a pair, "running through" all the elements of the array with our eyes. We will construct the algorithm for finding the maximum (minimum) element in such a way as to compare a pair of numbers, repeating the comparison action the required number of times.

So, we need to answer two questions:

1) what numbers are included in the pair that makes up the operation of the relation;

2) how many times it is necessary to repeat the comparison operation. Let's introduce an additional variable named max. It will be one of the numbers, the second number is the next element of the array. In order to carry out the first comparison operation, it is necessary to assign an initial value to the variable max. There are two options here:

1) assign the first element of the array to the variable max;

2) assign a number that is obviously less than all the elements of the array.

The array contains information about the number of students in each group of the 1st year. Determine the group with the maximum number of students, assuming that the group number corresponds to the ordinal number of the number in the array (we consider that such a group is the only one).

In other words, we have to find the maximum element and its number.

program max_num;

type mas = array [1 .. 10] of byte;

var a: mas;

num, i: byte;

max: byte;

begin

(fill block)

for i: = l to 7 do

readln (a [i]);

(search for the maximum and its number)

max: == 0;

(enter the smallest number for this array)

for i: = l to n do

if a [i]> max then begin

num: = i;

max: = a [i]

end;

writeln ("maximum number of students =", max);

writeln ("group number =", num);

end.

3) Find the minimum element among the even elements of the array.

Explanation: we cannot assign the first element of the array to the min variable, since it can be odd. Therefore, we must choose some very large number for this data type.

If we declare the elements of an integer array, then so the number will be +32767.

program min_even;

a: array of integer;

i: integer;

min: integer;

begin

for i: = l to 10 do beein

writeln ("enter the next array element");

readln (a [i]);

end;

min: = 32767;

for i: = l to 10 do

if (a [i]

if min = 32767 then writeln ("there are no even elements in the array") else writein ("the minimum element among the even elements of the array =", min)

end.

Please note: you need to check if the value of the min variable has changed, because even elements might not have been.

Other similar works that may interest you. Wshm>

8729. DEFINITION AND METHODS OF DEFINING THE FINAL MACHINE. SYNTHESIS PROBLEM. ELEMENTARY MACHINES 189.1 KB
Definition and methods of specifying a finite state machine. DEFINITION AND METHODS OF DEFINING THE FINAL MACHINE. Definition of a state machine. Methods for specifying a state machine.
3552. Individual homework in chemistry. Chemistry homework 475.47 KB
Guidelines include individual homework on the following topics: classes of inorganic compounds, chemical equivalent, atomic structure, chemical bond, chemical thermodynamics, chemical kinetics, concentration of solutions, ionic reactions and salt hydrolysis, redox reactions, electrochemical processes, properties of metals.
12127. Strategic minerals (PGM, Ni, Co, Cr, Cu) of the Paleoproterozoic layered basic massifs of the northeastern Fennoscandian shield 17.77 KB
A brief description of the development. Development advantages in comparison with analogues. An important aspect of the development is the ability to minimize the negative technogenic impact on the environment by dramatically reducing the extensive use of heavy mining and drilling equipment at the reconnaissance and prospecting stages. Areas of commercial use of the development.
9554. MATHEMATICS. METHODOLOGICAL GUIDE AND TASKS 268.34 KB
The academic discipline "Mathematics" is designed to implement state requirements for the minimum content and level of training of graduates of secondary vocational education.
18129. Creative tasks as a means of developing imagination 91.06 KB
The above studies reflect the diversity of scientific ideas and practical approaches to organizing the creative activity of students in the educational process, however, the aspect of purposeful provision of creative tasks to younger schoolchildren in the learning process as a means of developing imagination has not yet been studied enough. Based on the identified contradictions in the analysis of philosophical psychological and pedagogical literature, as well as as a result of studying the experience of elementary school work, the problem of research was formulated, which consists in a theoretical ...
19517. Development of technical specifications for automation of the Bukva store 155.63 KB
Competent sale of goods based on the requirements of the client, that is, consultation of specialists. Therefore, it is necessary that the store receives information about the state of the market and itself provides information to the market about the available goods and services. Interaction with the media consists in providing the store with data about itself for its goods and services - later, an advertisement for a laptop salon will be formed from this data, which is perceived by the market for goods and services. Expansion of types of goods Store advantages: Great experience ...
3548. Homework in chemistry and guidelines for their implementation 229.61 KB
These homework assignments are designed for the systematic work of students of all specialties on the chemistry course in accordance with the curriculum. Completing assignments contributes to the development of students' skills of independent work.
19091. ANALYSIS OF THE TECHNICAL DESCRIPTION AND BASIC TECHNICAL REQUIREMENTS FOR THE DEVELOPED STRUCTURE 911.42 KB
Server room (server room or simply server room) is a dedicated technological room with specially created and maintained conditions for the placement and operation of server and telecommunication equipment. The permissible temperature in the server room must be
1763. Implementation of the task in the form of a class using the container of the Standard Template Library (STL) of the C ++ language to store information 190.6 KB
The C ++ syntax is inherited from the C language. One of the design principles was to maintain compatibility with C. However, C ++ is not strictly a superset of C; many programs that can be equally successfully translated as C compilers ...
10124. Development of technical specifications for the provision of advertising services, cleaning services, security, staffing 31.88 KB
Development of technical specifications for advertising services: legal regulation of advertising services. Development of technical specifications for cleaning services: basic concepts and types of services. Development of technical specifications for security services: legal regulation. Development of technical specifications for staffing services: basic concepts.