Home‎ > ‎CS 11M‎ > ‎

### Contents1 Questions, Answers and Review2 Arrays2.1 Introduction to Arrays2.2 Strings and Character Arrays2.3 Try It: String Sizes2.4 Declaring and Initializing Arrays3 Exercise 1: Start with Arrays3.1 Check Yourself3.2 Arrays as Function Parameters4 Exercise 2: Exploring Arrays 4.1 Specifications4.2 Summary5 Exercise 3: Advanced Sensor Readings5.1 Specifications

• Questions from last class?
• Questions about labs or upcoming homework?

## Arrays

 Learner Outcomes At the end of the lesson the student will be able to: Declare and allocate memory for arrays Generate code to initialize arrays Access array elements Use arrays with functions

### Introduction to Arrays

• The most basic way to organize lists of the same type is to use arrays
• Arrays are a low-level construct and can be inconvenient (but are fast and use minimal memory)
• Arrays cannot be resized
• We usually create some extra space in each array and check to make sure we do not run out of room
• Arrays work in C and C++. C++ has more advanced ways to store lists.
• Arrays are fast and efficient.

#### Check Yourself

1. True or false: arrays cannot be resized.
2. True or false: we use arrays because they are the most convenient

### Strings and Character Arrays

• The C programming language has existed since the early 1970s. As computers have become more powerful the C (and eventually C++) language has gained features that make programming easier for the programmer at the cost of program performance.
• The place where C's evolution is most apparent is in how strings are stored and manipulated.
• strings are sequences of characters. They're important for human interaction. You've already used them extensively. The simplest form of string is a constant string. Here's an example:
`    cout << "Hello World" << endl;`
• So what is "Hello World" to C/C++? It's an array of characters. Each array element has one character in it. The first (left most) letter is the zeroth element in the array and the array has a hidden null element at the end. The picture shows the array that's generated by the above string:

• Notice the "null" character at the end of the string.
• Functions that use strings need to know where the string ends.
• Those functions read through the string until they see the null character ('\0').
• Forgetting the null character is one of the major pitfalls of using character arrays in C and C++.
• It's the most common cause of buffer overflow attacks on programs today.
The table below describes the evolving syntax of strings:
 Declaration Support Example ` char *s = "Hello World";` C/C++   Always ```void setup() {   Serial.begin(9600); }void p(char *s) {``` `  int i=0;``  cout << ("\"");` `  while (s[i] != '\0') {` `    cout << s[i];` `    i++;` `  } `` cout << "\" Length: " << i+1 << endl;``}` `void loop() {` `    char *s = "Hello World";` `  p(s);` `}` ` char s[] = "Hello World";` C/C++  Always ```void setup() {   Serial.begin(9600); } void p(char s[]) {``` `  int i=0;``  cout << "\"";` `  while (s[i] != '\0') {` `    cout << s[i];` `    i++;` `  }``  cout << "\" Length: " ``<< i+1 << endl;` `}` `void loop() {` `    char s[] = "Hello World";` `  p(s);` `}` ` string s = "Hello World";` C++98 ```#include void setup() {   Serial.begin(9600); }void p(string s) {``` `  cout << "\"" << ``s << ``"\" Length: " << ``s.size() << endl;` `}` `void loop() {` `  string s = "Hello World";` `  p(s);` `}` ` String s = "Hello World";` C++ Arduino Only ```void setup() {   Serial.begin(9600); }void p(String &s) {``` `  cout << "\"" << ``s << ``"\" Length: " << ``s.length() << endl;` `}` `void loop() {` `  String s = "Hello World";` `  p(s);``}`

### Try It: String Sizes

• Use each of the string types in a program
• Can you spot the difference between C-Strings and C++ strings?
• Why do you think the difference exists?

#### Use for C-Strings

• Many string functions in the standard library depend on `'\0'` terminators in character arrays
• For example, the following function returns the size of a C-string:
``````int strlen(const char s[]) {
int i = 0;
while (s[i] != '\0') {
i++;
}
return i;
}```
```
• This function will not work without the null `'\0'` terminator in the `char` array
• Generally we should use the `string` class and avoid using `char` arrays
• Arduino uses the String class (notice the upper case "S")
• The `String` class is safer and far more convenient
• Sometimes we need to convert a `string` into a C-string to call a function written before the string class was invented
• We can easily convert a `string` to a C-string using the `c_str()` member function
• For example, we may want to convert a `string` to a number using `atof()`, which needs a C-string argument:
``````string input = "9.99";
double num = atof(input.c_str());
cout << num << endl;```
```

#### Check Yourself

1. The size of the following C-string is ________.
``````char msg[] = "Hello";
``````
2. True or false: all C-strings require a '`\0`' character at the end, and an assignment statement adds one automatically.
3. True or false: some useful C functions require a C-string parameter and will not work with type `string`.
4. To convert a `string` to a C-string, use the `string` member function ________.

### Declaring and Initializing Arrays

• Declaring an array is easy:
````dataType` `variableName``[``size````];
``````
• Where:
• dataType: the data type of all the array items
• variableName: the name you make up for the array
• size: the number of data items the array can hold
• For example, the following is the declaration of an array named `scores` that holds 10 values of type `int`:
``int scores[10]``
• Arrays like this can never change size and the array size must be set when the program is compiled
• When defining an array, you must guess the maximum number of elements you need to store:
``````const int MAX_SCORES = 100;
int scores[MAX_SCORES];```
```
• The programmer must keep track of the capacity
• We use a constant to hold the capacity of the array as shown above
• This allows us to know the size anywhere in our code
• If we need to change the size, we change only a single constant and recompile

#### Initializing Array Items

• Like vectors, we specify which slot of an array to access with the `[]` operator:
``scores[4] = 98;``
• The indexes of arrays are numbered starting at 0, just like vectors
• We can assign a value to an array element any time after it is declared:
``````const int MAX_SCORES = 5;
int scores[MAX_SCORES];
scores[0] = 90;
scores[1] = 95;
scores[2] = 87;
scores[3] = 89;
scores[4] = 98; // fifth item```
```
• Unlike vectors, we can initialize array elements in the declaration statement:
• Called static initialization
• We use a comma-separated list inside curly-braces
• For example:
``````int scores[] = { 90, 95, 87, 89, 98 };
``````
• This produces the same array as in the previous example
• The compiler computes the size automatically by counting the items in the list
• If we want a larger array with only the first few elements initialized, we can use:
``````int scores[MAX_SCORES] = {90, 95, 87};
``````
• Note that if we do not assign a value to an array element, its value is not known

#### Example Program Using Arrays

`#include <ArduinoSTL.h>`

`using namespace std;`

`const int MAX_SCORES = 10;`

`void setup() {`
`  Serial.begin(9600);`
`}`

`void loop() {`
`  int scores[MAX_SCORES];`

`  cout << "Enter " << MAX_SCORES << " scores." << endl;`
`  for (int i = 0; i < MAX_SCORES; i++) {`
`    cin >> scores[i];`
`  }`

`  cout << "You entered: " << endl;`
`  for (int i = 0; i < MAX_SCORES; i++) {`
`    cout << scores[i] << endl;`
`  }`
`}`

Be sure to set your Serial Monitor to add newlines when trying the above.

• Change the second for loop to print the scores in REVERSE order.
• Change the number of recorded scores to 5
• When you're done save your program as `scores_array` and submit it with your next assignment.

#### Check Yourself

1. Enter the code to declare an array, named `myArray`, and allocate space for 10 values of type `double`.

2. The first element in any array has an index value of ________.
1. -1
2. 0
3. 1
4. 2
3. Of the following, ________ will correctly access the fifth element of an array named "foo".
1. `foo[5]`
2. `foo(5)`
3. `foo[4]`
4. `array.foo[4]`
4. Enter the code to declare an array, named `myArray`, allocate space for 5 doubles and assign the values 1.2, 2.3 and 3.4 to the first 3 elements.

5. True or false: the programmer must keep track of the size of an array, which should be stored in a constant.

### Arrays as Function Parameters

• When writing a function with an array parameter, we place an empty `[]` after the parameter name:
``````void print(int values[], int size);
``````
• We pass the size of the array to the function so the function knows the size of the array
• There is no `size()` member function for an array
• When we call the function, we do NOT include the `[]`:
``````print(data, size); // function call
``````
• Unlike other parameters, array parameters are always passed by reference
• However, we use `[]` rather than an `&` when declaring the array parameter
• For example:
``````void read(int data[], int capacity, int& size) {
size = 0;
while (size < capacity) {
cin >> data[size];
size++;
```    }
} ```
• Note the use of both the `capacity` and `size` parameters
• The `capacity` parameter tells the function the maximum array size
• The `size` parameter records how many items the user entered into the array
• The last part enters the data and verifies it was entered correctly
• The programmer must keep track of both the capacity and size when working with arrays
• Note that arrays cannot be function return types
• Since arrays are always passed by reference, then returning an array with a return statement is not necessary

#### Using the `const` Modifier

• Normally, a function can change the values of array elements
• We can prevent the modification using the `const` modifier:
``````void print(const int values[], int size);
``````
• The compiler will issue an error message if you try to change the value of an array element
• If a function with a constant array parameter calls another function using the `const` array parameter as an argument, the called function must use a `const` array parameter as well
• Otherwise, the compiler will issue an error
• The following program shows arrays used with functions

#### Example Program Using Arrays with Functions

`#include <ArduinoSTL.h>`

`using namespace std; `

`void setup() {`
`  Serial.begin(9600);`
`}`

`/**`
`    Fills an array with values from the keyboard.`

`    @param data The array to fill with data.`
`    @param capacity The capacity of the array.`
`    @param size The number of items entered.`
`*/`
`void read(int data[], int capacity, int& size) {`
`  size = 0;`
`  while (size < capacity) {`
`    cin >> data[size];`
`    if (cin.fail()) {`
`      string junk; `
`      cin >> junk;`
`      cin.clear();`
`      return;`
`    }`
`    size++;`
`  }`
`}`

`/**`
`    Displays an array to the screen`

`    @param data The array to fill with data.`
`    @param size The number of items in the array.`
`*/`
`void print(const int values[], int size) {`
`  for (int i = 0; i < size; i++) {`
`    cout << values[i] << endl;`
`  }`
`}`

`void loop() {`
`  const int MAX_ITEMS = 10;`
`  int data[MAX_ITEMS];`
`  int size = 0;`

`  cout << "Enter numbers ('q' to quit):" << endl;`
`  read(data, MAX_ITEMS, size);`

`  cout << "You entered:" << endl;`
`  print(data, size);`
`}`

## Exercise 2: Exploring Arrays

In this exercise we explore declaring, allocating and assigning values to arrays containing lists of data.

#### Specifications

1. Create the `myarrays.ino` file, complete the following exercise:
2. Add the following function to the code:

`void print(const int values[], int size) {`
`    for (int i = 0; i < size; i++) {`
`        cout << values[i] << " ";`
`    }`
`    cout << endl;`
`}`

3. Compile your code to make sure it has correct syntax.

If you have problems, ask a classmate or the instructor for help as needed.

4. Declare and initialize an array for a list of 10 integer scores after the current arrays using the following code:
``````const int NUM_SCORES = 10;
int scores[NUM_SCORES] = {90, 91, 92, 93, 94, 95, 96, 97, 98, 99};```
```

5. After declaring and initializing the array, call the `print()` function using the code:
``````cout << "Integer scores:";
print(scores, NUM_SCORES);```
```

6. Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like:
``````Integer scores:
90 91 92 93 94 95 96 97 98 99
``````
7. Declare and initialize an array of `double` values holding the temperatures `25.7``30.3` and `40.9` in order.

8. Write another `print()` function with two parameters: one for the array of `double` values and one for the size of the array.

9. After declaring and initializing the array, call the `print()` function.

10. Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like:
``````Integer scores:
90 91 92 93 94 95 96 97 98 99
Double temperatures:
25.7 30.3 40.9```
```
11. Declare and allocate an array of `char` values as a C-string and assign the C-string the vowels `'a', 'e', 'i', 'o'`, `'u' and '\0'`. (backslash-zero)

12. After declaring and initializing the array, display the C-string using the `cout` function.

13. Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like:
``````Integer scores:
90 91 92 93 94 95 96 97 98 99
Double temperatures:
25.7 30.3 40.9
C-string vowels:
aeiou```
```
14. Save your program source code to submit to Canvas as part of assignment 9.

#### Check Yourself

1. What is the syntax for declaring an array? (9.3.1)
2. Why must the programmer track both the capacity and number of elements used in an array? (9.3.1)
3. What are two ways to declare and initialize an array? (9.3.2)
4. What is the syntax of an array parameter? (9.3.3)
5. True or false? An array parameter is always pass by reference. (9.3.3)
6. What is a C-string? (9.3.4)
7. What is the ending character for a C-string? (9.3.4)
8. How large should you make a C-string? Why? (9.3.4)
9. What function can you use to convert a `string` to a C-string? (9.3.4)
10. What function can you use to convert a C-string to a `double`? (9.3.4)

### Summary

• In this section we looked at how to use arrays
• Arrays are a lower-level abstraction than vectors, so they are less convenient
• Vectors are a recent addition to C++, so many older programs use arrays instead
• Declaring an array is similar to declaring a vector:
``int scores[10]``
• Arrays can never change size and the array size must be set when the program is compiled
• When defining an array, we must guess on the maximum number of elements we need to store
• Then we must keep track of both the capacity and number of elements in use in an array
• When writing a function with an array parameter, we place an empty `[]` after the parameter name:
``````void print(int values[], int size);
``````
• We need to pass the size of the array into the function, because the function has no other way of knowing the size of the array
• Sometimes we must pass both the capacity and size of an array to a function:
``````void read(int data[], int capacity, int& size);
``````
• The `capacity` parameter tells the function the maximum array size
• The `size` parameter records how many items the user entered into the array
• Unlike all other parameters, array parameters are always passed by reference
• However, we never use an & when defining an array parameter
• Also note that functions cannot return arrays
• There was a time when C++ had no `string` class
• Instead, we used a variation of a `char` array often called a C-string
• Generally we should use the `string` class and avoid using `char` arrays
• The `string` class is safer and far more convenient
• Sometimes we need to convert a `string` into a C-string to call a function written before the string class was invented
• We can easily convert a `string` to a C-string using the `c_str()` member function:
``````string input = "9.99";
double num = atof(input.c_str());
cout << num << endl;``````

In this exercise you will write a function that reads values into an array then computes some information based on those readings.

`#include <ArduinoSTL.h>`

`using namespace std; `

`const int lightSensor = A0; `
`const int pressureSensor = A1; `

`void setup() {`
`  Serial.begin(9600);`
`}`

`void loop() {`
`  int sensor, count; `
`  cout << "Enter which sensor to read: 1 for light 2 for pressure." << endl;`
`  cin >> sensor; `
`  cout << "Enter how many readings to take." << endl;`
`  cin >> count; `

`  //`
`  // 1. Create an array to store the readings. `
`  // 2. Call getSensorReadings() `
`  // 3. Calculate the minimum, maximum and average reading. `
`  //`
`}`

`void getSensorReadings(int sensor, int readings[], int count) {`
`  `
`}`

### Specifications

• Add code to `getSensorReadings()` that fills the `readings[]` array with count consecutive readings from the sensor.
• In `loop()` examine the values in the array to determine the following:
• Name your program `sensor_readings.ino` and submit it with the next assignment.