# 6.3 — Arrays and loops

Consider the case where we want to find the average test score of a class of students. Using individual variables:

That’s a lot of variables and a lot of typing -- and this is just 5 students! Imagine how much work we’d have to do for 30 students, or 150.

Plus, if a new student is added, a new variable has to be declared, initialized, and added to the totalScore calculation. Any time you have to modify old code, you run the risk of introducing errors.

Using arrays offers a slightly better solution:

This cuts down on the number of variables declared significantly, but totalScore still requires each array element be listed individually. And as above, changing the number of students means the totalScore formula needs to be manually adjusted.

If only there were a way to loop through our array and calculate totalScore directly.

Loops and arrays

In a previous lesson, you learned that the array subscript doesn’t need to be a constant value -- it can be a variable. This means we can use a loop variable as an array index to loop through all of the elements of our array and perform some calculation on them. This is such a common thing to do that wherever you find arrays, you will almost certainly find loops! When a loop is used to access each array element in turn, this is often called iterating through the array.

Here’s our example above using a for loop:

This solution is ideal in terms of both readability and maintenance. Because the loop does all of our array element accesses, the formulas adjust automatically to account for the number of elements in the array. This means the calculations do not have to be manually altered to account for new students, and we do not have to manually add the name of new array elements!

Here’s an example of using a loop to search an array in order to determine the best score in the class:

In this example, we use a non-loop variable called maxScore to keep track of the highest score we’ve seen. maxScore is initialized to 0 to represent that we have not seen any scores yet. We then iterate through each element of the array, and if we find a score that is higher than any we’ve seen before, we set maxScore to that value. Thus, maxScore always represents the highest score out of all the elements we’ve searched so far. By the time we reach the end of the array, maxScore holds the highest score in the entire array.

Mixing loops and arrays

Loops are typically used with arrays to do one of three things:
1) Calculate a value (e.g. average value, total value)
2) Search for a value (e.g. highest value, lowest value).
3) Reorganize the array (e.g. ascending order, descending order)

When calculating a value, a variable is typically used to hold an intermediate result that is used to calculate the final value. In the above example where we are calculating an average score, totalScore holds the total score for all the elements examined so far.

When searching for a value, a variable is typically used to hold the best candidate value seen so far (or the array index of the best candidate). In the above example where we use a loop to find the best score, maxScore is used to hold the highest score encountered so far.

Sorting an array is a bit more tricky, as it typically involves nested loops. We will cover sorting an array in the next lesson.

Arrays and off-by-one errors

One of the trickiest parts of using loops with arrays is making sure the loop iterates the proper number of times. Off-by-one errors are easy to make, and trying to access an element that is larger than the length of the array can have dire consequences. Consider the following program:

The problem with this program is that the condition in the for loop is wrong! The array declared has 5 elements, indexed from 0 to 4. However, this array loops from 0 to 5. Consequently, on the last iteration, the array will execute this:

But scores is undefined! This can cause all sorts of issues, with the most likely being that scores results in a garbage value. In this case, the probable result is that maxScore will be wrong.

However, imagine what would happen if we inadvertently assigned a value to array! We might overwrite another variable (or part of it), or perhaps corrupt something -- these types of bugs can be very hard to track down!

Consequently, when using loops with arrays, always double-check your loop conditions to make sure you do not introduce off-by-one errors.

Quiz

1) Print the following array to the screen using a loop:

Hint: You can use std::size (as of C++17) or the sizeof() trick (prior to C++17) to determine the array length.

2) Given the array in question 1:

Ask the user for a number between 1 and 9. If the user does not enter a number between 1 and 9, repeatedly ask for an integer value until they do. Once they have entered a number between 1 and 9, print the array. Then search the array for the value that the user entered and print the index of that element.

You can test std::cin for invalid input by using the following code:

3) Modify the following program so that instead of having maxScore hold the largest score directly, a variable named maxIndex holds the index of the largest score.

Quiz solutions 6.4 -- Sorting an array using selection sort Index 6.2 -- Arrays (Part II)

### 319 comments to 6.3 — Arrays and loops

• Matthias

The solution to Quiz 1 is "wrong" in terms of it doesn't correspond to the array asked in the question.

• nascardriver

I broke it during an update and didn't notice, it's fixed now. Thanks!

• BooGDaaN

This is my solution for quiz 2. I hope this is ok.

• nascardriver

- `std::size` returns a `std::size_t`, which is an unsigned integer type, but not necessarily `unsigned int`.
- Use single quotation marks for characters (' ' instead of " ").

Rest looks good :)

• BooGDaaN

I updated the code. Thank you very much!

• gacrux

On code blocks 17.12 (also tried the 20191006 nightly):

||=== Build: Debug in 63 lesson (compiler: GNU GCC Compiler) ===|
C:\Users\admin\Documents\cbprojects\63 lesson\main.cpp|7|error: 'size' is not a member of 'std'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

https://en.cppreference.com/w/cpp/iterator/size
Defined in header <iterator> (since C++17)

Pretty sure the compiler is configured as shown in the very first lessons, already checked twice.

Even the example in cppreference shows the same error :(

• nascardriver

https://www.learncpp.com/images/CppTutorial/Chapter0/CB-C++11-min.png
This is the setting you need to look for, but you need at least C++17. If C++17 isn't available, you need to update GCC.

• Gacrux

The compiler is configured exactly as shown, but the error was still occurring.

Updating to MinGW-W64 GCC-8.1.0 (x86_64-posix-seh) fixed the issue.

For those interested: https://sourceforge.net/projects/mingw-w64/files/mingw-w64/

The toolchain have to be configured manually in the compiler settings for the new binaries.

• nascardriver

Thanks for posting how you fixed it. I suppose you were using an old version of gcc and codeblocks didn't tell you that -std=c++17 was unsupported.

• Chandler

For some reason, C::B is still using an old compiler (v5.1.x) with their IDE. You'll definitely have to upgrade your compiler to have C++17 capabilities. I'm using Qt 5.13.2 and it ships with MinGW 7.3.0 and is 100% C++17 compliant.

• Kim Stewart

Write a program that reads 10 scores of a student, then find a average 10 scores, a number of passing score and a number of failing score.

Assume that possible score is 100
Passing score is 50 and above
Failing score is 49 and below

• nascardriver

Where are you stuck? What have you tried? Why didn't it work?

• Kim Stewart

I tried to put numbers all together with int but, get did not work, can you show me  how  I should it be done, and thanks in advance.

• nascardriver

Show me your current code and mark what exactly you need help with. I won't do your homework for you.

• Sam

Here is my solution for Question #3

• nascardriver

- Initialize your variables with brace initializers.
- Compile-time constants should be `constexpr`.
- Line 2: "C++14" :)

• Sam

fixed :)