Abstract
An array enables you to work with several data items of the same type using a single name, the array name. The need for this occurs often—when working with a series of temperatures or the ages of a group of people, for example. A loop is another fundamental programming facility. It provides a mechanism for repeating one or more statements as many times as your application requires. Loops are essential in the majority of programs. Using a computer to calculate the company payroll, for example, would not be practicable without a loop. There are several kinds of loop, each with their own particular area of application.
Access this chapter
Tax calculation will be finalised at checkout
Purchases are for personal use only
Notes
- 1.
Without going too much into the specifics, statements such as count += height[i] < average; are sometimes produced by “clever” C++ programmers because they assume they will run faster than the original conditional statement if (height[i] < average) ++count; (because the latter contains a so-called branching statement). The fact is that any self-respecting compiler will already rewrite this code for you in a similar manner. Our advice is that it’s almost always best to leave the cleverness to the compiler; your job should be, in the first place, to produce code that is correct and clearly readable.
- 2.
Technically, std::size() is primarily defined in the iterator header. But because it is such a commonly used utility, the Standard Library guarantees it to be available also when the array header is included (and with several other headers as well). Since you’ll mostly use std::size() with arrays, we believe it is easier to remember to include the array header instead of the iterator header.
- 3.
If the for loop’s body contains continue statements (covered later in this chapter), you’ll need some additional work rewriting the loop to a while loop. Concretely, you’ll have to ensure a copy of the iteration code is added prior to every continue statement.
Author information
Authors and Affiliations
Rights and permissions
Copyright information
© 2018 Ivor Horton and Peter Van Weert
About this chapter
Cite this chapter
Horton, I., Van Weert, P. (2018). Arrays and Loops. In: Beginning C++17. Apress, Berkeley, CA. https://doi.org/10.1007/978-1-4842-3366-5_5
Download citation
DOI: https://doi.org/10.1007/978-1-4842-3366-5_5
Published:
Publisher Name: Apress, Berkeley, CA
Print ISBN: 978-1-4842-3365-8
Online ISBN: 978-1-4842-3366-5
eBook Packages: Professional and Applied ComputingProfessional and Applied Computing (R0)Apress Access Books