Static array: declaration, filling, use. One-dimensional arrays Ways to enumerate array elements c

An array is a data structure represented as a group of cells of the same type, united under one single name. Arrays are used to process large amounts of data of the same type. The name of the array is what pointers are, I’ll tell you a little later. An individual data cell of an array is called an array element. The elements of an 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 an n-dimensional array. One-dimensional and two-dimensional arrays are most often used in programming, so we will consider only these arrays.

One-dimensional arrays in C++

One-dimensional array is 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 have only one row and n number of 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 is 15, but the size of the array is 16 cells, because the numbering of array cells always starts from 0. The cell index is a non-negative integer by which you can access each cell of 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*/; //an example of declaring a one-dimensional array shown in Figure 1: int a;

where, int is an integer;

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

Always immediately after the name of the array there are square brackets in which the size of the one-dimensional array is specified; this is what distinguishes the array 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 ); // initialization of a one-dimensional array

Initialization of a one-dimensional array is performed in curly braces after the sign equals, each array element 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); // initializing the array without determining its size.

In this case, the compiler itself will determine the size of the one-dimensional array. The size of an array can only be omitted when initializing it; when declaring an array normally, the size of the array must be specified. Let's develop a simple program to process 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; }

IN lines 10 - 11 An integer one-dimensional array named array1 has been declared and initialized, the size of which is 16 cells, that is, such an array can store 16 numbers. Any array processing is only possible in conjunction with loops. Which loop to choose for processing the array is up to you to decide. But it is best suited for this task. We will use the counter variable counter to access the elements of the one-dimensional array array1. The continuation condition 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, there are 16 elements in the array. In the body of the for loop, the cout operator prints the elements of a one-dimensional array (see Figure 2).

Obrabotka massiva indexes 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 To continue, press any key. . .

Figure 2 - Arrays in C++

Let's develop another program for processing a one-dimensional array in C++. The program must sequentially read ten entered numbers from the keyboard. All entered numbers are summed up and the result is displayed on the screen.

// 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 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 an array, it must be declared, and the size of a one-dimensional array is 10, as this is stipulated by the condition of the task. In the sum variable we will accumulate the sum of the elements of a one-dimensional array. The first for loop fills the declared one-dimensional array with numbers entered from the keyboard, lines 12 - 13. The counter variable is used to sequentially access the elements of the one-dimensional array array1 , starting from index 0 and up to the 9th inclusive. The second for loop displays the elements of the array, lines 15 - 16. The third for loop sequentially reads the elements of a one-dimensional array and sums them, the sum is accumulated in the sum variable. lines 17 - 18. The result of the program is shown 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 To continue, press any key. . .

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 numbers in the array 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. A table has two characteristics: 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 such characteristics as the number of rows and the number of columns of a two-dimensional array. That is, visually, a two-dimensional array is a regular 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, of size m by n is shown below (see Figure 4).

Figure 4 - Arrays in C++

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

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

In declaring a two-dimensional array, as well as in declaring a one-dimensional array, first of all, you need to specify:

  • data type;
  • array name.

After that, the first square brackets indicate the number of rows of the two-dimensional array, and the second square brackets indicate the number of columns of the two-dimensional array. A two-dimensional array is visually distinguished from a one-dimensional one by a second pair of square brackets. Let's look at an example of declaring a two-dimensional array. Let's say we need to declare a two-dimensional array with a 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 declaration of a two-dimensional array: int a;

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

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

This array has 5 rows, 3 columns. after the assign sign, general curly brackets are placed, inside which as many pairs of curly brackets are placed 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. In all curly braces, the number of elements must be the same. Since there are five lines in the array, there are also five inner pairs of brackets. Three elements are written in the inner brackets, 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, called “Labyrinth”. The labyrinth must be built on the basis of a two-dimensional array. We will choose the size of the labyrinth 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);<< static_castcout<< " "; // вывести два пробела cout << endl; } system("pause"); return 0; }

// code Code::Blocks

// Dev-C++ code

(176); using namespace std; int main(int argc, char* argv) ( // 1-conditionally “walls of the maze” // 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,), // 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,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,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,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,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,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,2,1,), (1,2,1,1,2,1,1,0,1,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,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,1,), (1,2 ,1,1,2,1,0,1,1,2,1,1,2,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,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 - internal and external, accessing 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);<< static_castcout<< " "; // вывести два пробела 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, only to simplify the program. Since the program processes a two-dimensional array, two loops are needed to switch between elements of the two-dimensional array. The first for loop switches between rows of a two-dimensional array. Since there are 33 rows in a two-dimensional array, the counter variable i is incremented from 0 to 33, line 46. Inside the first loop is a for loop that cycles through the row elements of a two-dimensional array. In the body of the second for loop, a unary data type conversion operation is performed inside - static_cast<>() , which prints character number 176. The data type conversion operation is duplicated to increase the width of the maze. The result of the program (see Figure 6).

Figure 6 - Arrays in C++

Arrays

Array is a collection of variables of the same type with a common name to refer to them. In C#, arrays can be either one-dimensional or multi-dimensional. Arrays serve a variety of purposes because they provide a convenient means of grouping variables together that are related together.

You can use arrays in C# in much the same way as in other programming languages. However, they have one peculiarity: they are implemented as objects.

Using an array in a program requires a two-step procedure because C# implements arrays as objects. First, you need to declare a variable that can access the array. And secondly, you need to create an instance of the array using the new operator.

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 ( class Program ( static void Main(string args) ( // Declare the array int myArr = new int; // Initialize each element of the array manually myArr = 100; myArr = 23; myArr = 25; myArr = 31; myArr = 1 ; foreach (int i in myArr) Console.WriteLine(i);

Keep in mind that if an array is just declared but not explicitly initialized, each element will be set to the default value for the corresponding data type (for example, elements of an array of type bool will be set to false, and elements of an array of type int will be set to 0).

Initializing an Array

In addition to filling the array element by element (as shown in the previous example), you can also fill it using a special array initialization syntax. To do this, you need to list the elements included in the array in curly braces ( ). This syntax is useful when creating an array of known size and needing to quickly set its initial values:

// Syntax for initializing an array using // the keyword new int myArr = new int (10,20,30,40,50); // Syntax for initializing an array without using // a keyword new string info = ( "Last Name", "First Name", "Patronymic" ); // Use the new keyword and the desired size char symbol = new char ( "X","Y","Z","M" );

Note that when using curly brace syntax, you do not need to specify the size of the array (as seen in the creation of the myArr variable) because the size is automatically calculated based on the number of elements inside the curly braces. Also, use the keyword new optional (as when creating an info array).

The var keyword allows you to define a variable so that its underlying type is inferred by the compiler. You can also define implicitly typed local arrays in a similar way. Using this approach, you can define a new array variable without specifying the type of elements contained in the array. Let's look at an example:

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 ( class Program ( static void Main(string args) ( var arr1 = new ( 1, 2, 3 ); Console.WriteLine("Array type arr1 is (0)",arr1.GetType()); var arr2 = new ( "One", "Two", "Three" ); Console.WriteLine("Array type arr2 - (0)",arr2.GetType());

Of course, just as when creating an array using explicit C# syntax, the elements specified in the array initialization list must be of the same underlying type (that is, they must all be int, string, or MyCar).

Defining an Array of Objects

In most cases, when defining an array, the type of the element contained in the array is specified explicitly. Although this seems pretty straightforward at first glance, there is one important feature. At the heart of every type in the .NET type system (including fundamental data types) is ultimately a base class, System.Object. The result is that if you define an array of objects, the elements inside it can be anything:

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 ( class Program ( static void Main(string args) ( // Declare and initialize an array of objects object arrByObject = ( true, 10, "Hello", 13.7m ); // Print the type of each array member to the console foreach (object me in arrByObject) Console.WriteLine("Type (0) - (1)",me,me.GetType());

Let us say we need to work with a large amount of data of the same type. For example, we have a thousand measurements of the coordinates of a pendulum with some time step. Creating 1000 variables to store all the values ​​is very... cumbersome. Instead, many of the same type of data can be combined under one name and each specific element can be accessed by its serial number.
An array in C is defined as follows
<тип> <имя массива>[<размер>];
For example,
int a;
We will receive an array named a, which contains one hundred elements of type int. As with variables, the array contains garbage.
To gain access to the first element, write its number (index) in square brackets. For example

#include #include void main() ( int a; a = 10; a = 333; a = 234; printf("%d %d %d", a, a, a); getch(); )

The first element has index number 0. It is important to understand why. In what follows, we will represent computer memory as a tape. The array name is a pointer to the memory address where the array elements are located.

Rice. 1 The array stores the address of the first element. The index of the i element is a shift of i*sizeof(type) bytes from the beginning

The array index indicates how many bytes must be shifted from the beginning of the array to access the desired element. For example, if the array A has type int, then A means that we have moved 10*sizeof(int) bytes relative to the beginning. The first element is at the very beginning and has an offset of 0*sizeof(int) .
In C, an array does not store its size and does not check the array index for correctness. This means that you can go outside the array and access memory that is further than the last element of the array (or closer).

Initial initialization of the array.

Let's write a simple program. Let's create an array and then find its maximum element.

#include #include void main() ( int a = (1, 2, 5, 3, 9, 6, 7, 7, 2, 4); unsigned i; int max; max = a; for (i = 1; i<10; i++) { if (a[i] >

Let's look at an example. We first create the array and initialize it upon creation. After this, we assign the maximum found element the value of the first element of the array.

Max = a;

Then we go through the array. Since we have already looked at the first element (it has index 1), there is no point in looking at it again.
Same example, only now the user enters values

#include #include void main() ( int a; unsigned i; int max; printf("Enter 10 numbers\n"); for (i = 0; i<10; i++) { printf("%d. ", i); scanf("%d", &a[i]); } max = a; for (i = 1; i<10; i++) { if (a[i] >max) ( max = a[i]; ) ) printf("max element is %d", max);

getch(); )

#include #include If during initialization fewer values ​​are specified than the size of the array, the remaining elements are filled with zeros.<10; i++) { printf("%d ", a[i]); } getch(); }

void main() ( int a = (1,2,3); unsigned i; for (i = 0; i

If you need to fill the entire array with zeros, then write

Int a = (0);

You don't have to specify the size of the array explicitly, for example

Int a = (1, 2, 3);

the array will have size 3

Array size

An array in C must have a constant size. This means that it is impossible, for example, to ask the user for a size and then set this size to an array.

Printf("Enter length of array "); scanf("%d", &length); ( float x; )
Creating dynamic arrays will be discussed further when working with pointers and memory In some cases, you can find out the size of the array using the function

#include #include sizeof.

void main() ( int A; //sizeof returns the size of the entire array in bytes //To determine the number of elements, //divide the size of the array by the size of its element int size = sizeof(A) / sizeof(int); printf("Size of array equals to %d", size); getch(); )
But this is unlikely to be useful. When passing an array as an argument to a function, a pointer will be passed, so the size of the array will not be known.

Static arrays are useful when the number of elements is known in advance. They provide fast but insecure access to elements.

Array overflow

Let's hope you have this code<=10; i++) { A[i] = 1; }

Int A; int i; for (i=0; i Here's a loop for specified with an error. In some older versions of compilers, this code would loop. The point is that the variable i A was located during compilation immediately after the array
. When the array went beyond the boundaries, the counter was set to 1.
Arrays are unsafe, since incorrect work with the index can lead to access to an arbitrary portion of memory (Theoretically. Modern compilers themselves take care that you do not delve into someone else's memory).

  • If you work with arrays, you need to ensure that the counter does not exceed the size of the array and is not negative. For this, at a minimum,
  • 2. Remember that the array starts from zero.
  • 3. The last element of the array has an index (array size is 1)
There are no full-fledged ways to check whether we have gone beyond the array or not. Therefore, either we know its size exactly, or we store it in a variable and read it when necessary.

Examples

Now here are some typical examples of working with arrays
1. Reverse the array.

#include #include //This is a macro. SIZE in the code will be replaced by 10u #define SIZE 10u void main() ( int A = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9); unsigned i, j; //counters unsigned half; //middle of the array unsigned tmp; //temporary variable for exchanging values ​​half = SIZE / 2; //One counter goes from left to right, the other from right to left for (i = 0, j = SIZE - 1; i< half; i++, j--) { tmp = A[i]; A[i] = A[j]; A[j] = tmp; } for (i = 0; i < SIZE; i++) { printf("%d ", A[i]); } getch(); }

Here is a design unfamiliar to you

#define SIZE 10u

macro. Throughout the code, the preprocessor will automatically replace all occurrences of SIZE with 10u.
2. Deleting an element selected by the user.

#include #include #define SIZE 10u void main() ( int A = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9); unsigned i; //counter int index; //index entered by the user / /Output array for (i = 0; i< SIZE; i++) { printf("(%d)=%d ", i, A[i]); } //Просим пользователя ввести валидный индекс while (1) { printf("\nEnter index of element to delete "); scanf("%d", &index); if (index >0 && index< SIZE) { break; } } //Копируем следующий элемент массива на место удаляемого //и так до конца for (i = index; i < SIZE-1; i++) { A[i] = A; } //Выводим результат for (i = 0; i < SIZE-1; i++) { printf("(%d)=%d ", i, A[i]); } getch(); }

In this case, of course, the element is not deleted. The array remains the same size as before. We simply overwrite the element being deleted with the next one and output SIZE-1 elements.
3. The user enters values ​​into the array. After that, print out all the different values ​​he entered.
Let the user enter a finite number of elements, say 10. Then it is known in advance that there will be no more than 10 different values ​​in total. Each time the user enters a number, we will go through the array and check whether such a number was entered.

#include #include #define SIZE 10u void main() ( int A = (0); unsigned i, j; int counter = 1; //how many different numbers are entered. At least one. int input; int wasntFound; //flag that the entered number was not found //Enter the first number. It has not been found yet. printf("0.");< SIZE; i++) { printf("%d. ", i); scanf("%d", &input); wasntFound = 1; //Проверяем, встречалось ли такое число. Если да, //то выставляем флаг и выходим из цикла for (j = 0; j <= counter; j++) { if (input == A[j]) { wasntFound = 0; break; } } //Если флаг был поднят, то заносим число в массив if (wasntFound) { A = input; counter++; } } for (i = 0; i < counter; i++) { printf("%d ", A[i]); } getch(); }

4. The user enters a number - the number of measurements (from 2 to 10). After this, enters all measurements. The program displays the average value, variance, and error.

#include #include #include #define SIZE 20u void main() ( //Student coefficients start from two dimensions const float student = (12.7, 4.3, 3.2, 2.8, 2.6, 2.4, 2.4, 2.3, 2.3); float A; unsigned i; unsigned limit; float sum = .0f; float disp; float relError; do (printf("Enter number of measurements "); scanf("%u", &limit); if (limit > 1 && limit< 11) { break; } } while(1); for (i = 0; i < limit; i++) { printf("#%d: ", i); scanf("%f", &A[i]); sum += A[i]; } mean = sum / (float)limit; sum = .0f; for (i = 0; i < limit; i++) { tmp = A[i] - mean; sum += tmp * tmp; } disp = sum / (float)limit; absError = student * sqrt(sum / (float)(limit - 1)); relError = absError / mean * 100; printf("Mean = %.6f\n", mean); printf("Dispertion = %.6f\n", disp); printf("Abs. Error = %.6f\n", absError); printf("Rel. Error = %.4f%", relError); getch(); }

5. Array bubble sort

#include #include #define SIZE 10 #define false 0 #define true !false void main() ( float a = (1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 0.0 f); float tmp; unsigned i, j; char flag; //Output array for (i = 0; i< SIZE; i++) { printf("%.3f ", a[i]); } printf("\n"); //Пока массив не отсортирован do { flag = false; //Проходим по массиву. Если следующий элемент больше предыдущего, то //меняем их местами и по новой проверяем массив for (i = 1; i < SIZE; i++) { if (a[i] >a) ( tmp = a[i]; a[i] = a; a = tmp; flag = true; ) ) ) while(flag == true);< SIZE; i++) { printf("%.3f ", a[i]); } getch(); }

//Output the sorted array for (i = 0; i

6. Mix the array. Let's use the algorithm for this

What are arrays in C?

How to declare arrays in C?

How to initialize arrays in C?

Arrays in C for dummies.

Arrays in C

An array in C is a collection of elements of the same type that can be accessed by index. The elements of arrays in C are located one after another in the computer's memory.

A simple example of creating and filling an array in C:

// @author Subbotin B.P..h> void main(void) ( int nArr; nArr = 1; nArr = 2; nArr = 3; printf("\n\tArray\n\n"); printf("nArr\t =\t%d\n", nArr); printf("nArr\t=\t%d\n", nArr); printf("nArr\t=\t%d\n", nArr); return 0 ; )

We get:

In the example, we declare an array containing elements of type int:

here the array name is nArr, the number of array elements is three, the array element type is int.

An array is a collection of elements. Each element of the array can be referred to by its number. The number is usually called an index. The array elements are numbered starting from zero. Let's assign a value to the first element of the array, and the first element has index zero:

Let's assign a value to the second element of the array, and the second element has index one:

Let's assign a value to the third element of the array, and the third element has index two:

When we display array elements on the screen, we get their values. Like this:

printf("nArr\t=\t%d\n", nArr);

To get an element of an array, you need to specify the name of the array and the index of the element:

This is the first element of the array, because the first element has index zero.

Let's assign the value of the third element of the array to the variable int a:

the index of the third element of the array is two, since indices are counted from zero.

Now the general rule for declaring arrays in C: when declaring an array, you need to indicate its name, type of elements, and number of elements. The number of elements is a natural number, i.e. the whole is positive. Zero cannot be the number of elements. You cannot specify a variable number of array elements. Here are examples of array declarations in C:
int nArr; // An array has been declared to hold one hundred integers;
char cArr; // An array has been declared to store two characters;

It would be a mistake to declare an array with a variable number of elements:

Int varElem;
int nArr; // Error! The number of elements cannot be set to a variable;

But you can set the number of elements with a constant value: either a direct positive integer 1, 2, 3... or a constant:

Const int arrayLength = 3;
int nArr;

When declaring an array in C, you can immediately initialize it:

int nMassiv = (1, 2, 3);

You can omit the number of array elements in square brackets if all array elements are initialized:

int nMassiv = (1, 2, 3);

the number of elements will be determined automatically in this case.

You can define only part of the elements of an array when declaring it:

int nMassiv = (1, 2);

in this example, the first two elements of the array are initialized, but the third is undefined.

Example of a character array:

char cArr = ("S", "B", "P");

When declaring an array, you cannot specify the number of elements of a variable. But you can use variables when accessing array elements:

Int ind = 0;
char cr = cArr;

This is used when working with loops. Example:

// @author Subbotin B.P..h> void main(void) ( const int arrayLength = 3; int nArr; for(int inn = 0; inn< 3; inn++) { nArr = inn + 1; } printf("\n\tArray\n\n"); for(int inn = 0; inn < 3; inn++) { printf("nArr[%d]\t=\t%d\n", inn, nArr); } return 0; }

In the example, in the first loop we fill the array with elements of type int, and in the second loop we display these elements on the screen.

mob_info