7.4.1. Declaring an array and Using a Loop to Initialize the array’s Elements

The program in Fig. 7.3 declares five-element integer array n (line 10). Line 5 includes the <array> header, which contains the definition of class template array. Lines 13–14 use a for statement to initialize the array elements to zeros. Like other automatic variables, automatic arrays are not implicitly initialized to zero although static arrays are. The first output statement (line 16) displays the column headings for the columns printed in the subsequent for statement (lines 19–20), which prints the array in tabular format. Remember that setw specifies the field width in which only the next value is to be output.


 1   // Fig. 7.3: fig07_03.cpp
 2   // Initializing an array's elements to zeros and printing the array.
 3   #include <iostream>
 4   #include <iomanip>
 5   #include <array>
 6   using namespace std;
 7
 8   int main()
 9   {
10      array< int, 5 > n; // n is an array of 5 int values
11
12      // initialize elements of array n to 0          
13      for ( size_t i = 0; i < n.size(); ++i )         
14         n[ i ] = 0; // set element at location i to 0
15
16      cout << "Element" << setw( 13 ) << "Value" << endl;
17
18      // output each array element's value                      
19      for ( size_t j = 0; j < n.size(); ++j )                   
20         cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl;
21   } // end main


Element        Value
      0            0
      1            0
      2            0
      3            0
      4            0


Fig. 7.3. Initializing an array’s elements to zeros and printing the array.

In this program, the control variables i (line 13) and j (line 19) that specify array subscripts are declared to be of type size_t. According to the C++ standard size_t represents an unsigned integral type. This type is recommended for any variable that represents an array’s size or an array’s subscripts. Type size_t is defined in the std namespace and is in header <cstddef>, which is included by various other headers. If you attempt to compile a program that uses type size_t and receive errors indicating that it’s not defined, simply include <cstddef> in your program.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.198.21