# Arrays

(defining-and-initializing-an-array-examples)=
## Defining and initializing an array

```{literalinclude} ../code/arrays_defining_initializing_using.c
:language: c
```
:::{dropdown} Output
```{literalinclude} ../code/arrays_defining_initializing_using.txt
:language: text
```
:::

:::{wpd} Array (data structure)
A data structure consisting of a collection of elements (values or variables), of same memory size, each identified by at least one array index or key.
:::


:::{activity}
:label: array-or-not
Which of the following correctly define and/or initialize an array?

1. `int array[];`{l=c}
1. `int array;`{l=c}
1. `char[] choices = {"black bird", "great tit", "falcon"};`{l=c}
1. `char names[] = {"ird", "grea", "con"};`{l=c}
1. `int part_ids[]= {3093, -49318, 3092.812};`{l=c}
1. `string names[] = [];`{l=c}
1. `double intensity[X][Y][Z];`{l=c}
:::

:::{activity}
Visualize the memory layout of `robot_names_v*` using the debugger:
1. set a breakpoint on the first line of `main()`.
1. <kbd>F5</kbd>
1. On the left click on `Variables` => `Global`.
1. Hover on a variable and click on the icon {{file_binary}}.
1. You will be asked if you want to install `Hex Editor`. Install it.
1. `memory.bin` file will be opened.

Answer the questions:
1. Localize both `robot_names_v*`.
1. What is the difference in their memory layout?
:::

## `sizeof` and `_Countof` operators

`sizeof` operator returns the size of an object in bytes.

`_Countof` operator returns the size of an array. It is similar to:

```
#define _Countof(arr) (sizeof(arr) / sizeof((arr)[0]))
```

## `size_t` datatype

If you use the output of a `sizeof` or `_Countof` operator in a loop, then use `size_t` – for example in a `for` loop.

## `for` loop statement

Used to repeat an operation over every element of an array. This is also called *iterating over an array*.

```c
for (
    initialize;
    check_before_each_repetition;
    do_after_the_repetition
    ) {
    operations;
}
```

You can also *nest* for loops:
```{literalinclude} ../code/arrays_iterating_3d.c
:language: c
```
:::{dropdown} Output
```{literalinclude} ../code/arrays_iterating_3d.txt
:language: text
```
:::

:::{activity}
Write a for loop for `caloriesEachDayEachMeal` above with the following requirements:
- prints all the data in the array. 
- Each data should be in its own row.
- uses `_Countof`.
:::


## Useful operations

Searching for an element and modifying an element

```{literalinclude} ../code-wi/arrays_operations.c
:language: c
```

<!--
probably I need programoutput

:::{dropdown} Output
```{literalinclude} ../code/arrays_operations.txt
:language: text
```
:::
-->