* remove "\r" nonsense
[mascara-docs.git] / C / the.ansi.c.programming.language / c.programming.notes / sx4a.html
blob2c4bbc8c3a6be74f7a9971c92b23a6c5601cf4ca
1 <!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995-7 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
5 <html>
6 <head>
7 <link rev="owner" href="mailto:scs@eskimo.com">
8 <link rev="made" href="mailto:scs@eskimo.com">
9 <title>4.1 Arrays</title>
10 <link href="sx4.html" rev=precedes>
11 <link href="sx4aa.html" rel=precedes>
12 <link href="sx4.html" rev=subdocument>
13 </head>
14 <body>
15 <H2>4.1 Arrays</H2>
17 <p>So far, we've been declaring simple variables:
18 the declaration
19 <pre>
20 int i;
21 </pre>
22 declares a single variable, named <TT>i</TT>, of type <TT>int</TT>.
23 It is also possible to declare an <dfn>array</dfn> of several elements.
24 The declaration
25 <pre>
26 int a[10];
27 </pre>
28 declares an array, named <TT>a</TT>, consisting of ten elements,
29 each of type <TT>int</TT>.
30 Simply speaking, an array is a variable that can hold
31 more than one value.
32 You specify which of the several values you're referring to at
33 any given time by using a numeric <dfn>subscript</dfn>.
34 (Arrays in programming are similar to
35 vectors or matrices in mathematics.)
36 We can represent the array <TT>a</TT> above with a picture like this:
37 <img src="fig4.1.gif"></p><p>In C, arrays are <dfn>zero-based</dfn>:
38 the ten elements of a 10-element array are numbered from 0 to 9.
39 The subscript which specifies a single element of an array
40 is simply an integer expression
41 in square brackets.
42 The first element of the array is <TT>a[0]</TT>,
43 the second element is <TT>a[1]</TT>, etc.
44 You can use these ``array subscript expressions''
45 anywhere you can use the name of a simple variable,
46 for example:
47 <pre>
48 a[0] = 10;
49 a[1] = 20;
50 a[2] = a[0] + a[1];
51 </pre>
52 Notice that the subscripted array references
53 (i.e. expressions such as <TT>a[0]</TT> and <TT>a[1]</TT>)
54 can appear on either side of the assignment operator.
55 </p><p>The subscript does not have to be a constant like <TT>0</TT> or <TT>1</TT>;
56 it can be any integral expression.
57 For example,
58 it's common to loop over all elements of an array:
59 <pre>
60 int i;
62 for(i = 0; i &lt; 10; i = i + 1)
63 a[i] = 0;
64 </pre>
65 This loop sets all ten elements of the array <TT>a</TT> to 0.
66 </p><p>Arrays are a real convenience for many problems,
67 but there is not a lot that C will do with them for you
68 automatically.
69 In particular,
70 you can neither set all elements of an array at once
71 nor assign one array to another;
72 both of the assignments
73 <pre>
74 a = 0; /* WRONG */
75 </pre>
76 and
77 <pre>
78 int b[10];
79 b = a; /* WRONG */
80 </pre>
81 are illegal.
82 </p><p>To set all of the elements of an array to some value,
83 you must do so one by one,
84 as in the loop example above.
85 To copy the contents of one array to another,
86 you must again do so one by one:
87 <pre>
88 int b[10];
90 for(i = 0; i &lt; 10; i = i + 1)
91 b[i] = a[i];
92 </pre>
93 Remember that for an array declared
94 <pre>
95 int a[10];
96 </pre>
97 there is no element
98 <TT>a[10]</TT>; the topmost element is <TT>a[9]</TT>.
99 This is one reason that zero-based loops are also common in C.
100 Note that the <TT>for</TT> loop
101 <pre>
102 for(i = 0; i &lt; 10; i = i + 1)
104 </pre>
105 does just what you want in this case: it starts at 0, the
106 number 10 suggests (correctly) that it goes through 10
107 iterations, but the less-than comparison means that the last
108 trip through the loop has <TT>i</TT> set to 9.
109 (The comparison <TT>i &lt;= 9</TT> would also work,
110 but it would be less clear and therefore poorer style.)
111 </p><p>In the little examples so far,
112 we've always looped over all 10 elements of the sample array <TT>a</TT>.
113 It's common,
114 however,
115 to use an array that's bigger than necessarily needed,
116 and to use a second variable
117 to keep track of how many elements of the array are currently in use.
118 For example, we might have an integer variable
119 <pre>
120 int na; /* number of elements of a[] in use */
121 </pre>
122 Then,
123 when we wanted to do something with <TT>a</TT>
124 (such as print it out),
125 the loop would run from 0 to <TT>na</TT>,
126 not 10
127 (or whatever <TT>a</TT>'s size was):
128 <pre>
129 for(i = 0; i &lt; na; i = i + 1)
130 printf("%d\n", a[i]);
131 </pre>
132 Naturally, we would have to ensure ensure that <TT>na</TT>'s value
133 was always less than or equal to
134 the number of elements actually declared in <TT>a</TT>.
135 </p><p>Arrays are not limited to type <TT>int</TT>;
136 you can have arrays of <TT>char</TT> or <TT>double</TT> or any
137 other type.
138 </p><p>Here is a slightly larger example of the use of arrays.
139 Suppose we want to investigate the behavior of rolling a pair of dice.
140 The total roll can be anywhere from 2 to 12,
141 and we want to count how often each roll comes up.
142 We will use an array to keep track of the counts:
143 <TT>a[2]</TT> will count how many times we've rolled 2, etc.
144 </p><p>We'll simulate the roll of a die by calling C's random number
145 generation function, <TT>rand()</TT>.
146 Each time you call <TT>rand()</TT>,
147 it returns a different, pseudo-random integer.
148 The values that <TT>rand()</TT> returns
149 typically span a large range,
150 so we'll use C's <dfn>modulus</dfn> (or ``remainder'')
151 operator <TT>%</TT> to produce random numbers in the range we want.
152 The expression <TT>rand() % 6</TT> produces random
153 numbers in the range 0 to 5,
154 and <TT>rand() % 6 + 1</TT> produces random
155 numbers in the range 1 to 6.
156 </p><p>Here is the program:
157 <pre>
158 #include &lt;stdio.h&gt;
159 #include &lt;stdlib.h&gt;
161 main()
163 int i;
164 int d1, d2;
165 int a[13]; /* uses [2..12] */
167 for(i = 2; i &lt;= 12; i = i + 1)
168 a[i] = 0;
170 for(i = 0; i &lt; 100; i = i + 1)
172 d1 = rand() % 6 + 1;
173 d2 = rand() % 6 + 1;
174 a[d1 + d2] = a[d1 + d2] + 1;
177 for(i = 2; i &lt;= 12; i = i + 1)
178 printf("%d: %d\n", i, a[i]);
180 return 0;
182 </pre>
183 We include the header <TT>&lt;stdlib.h&gt;</TT>
184 because it contains the necessary declarations
185 for the <TT>rand()</TT> function.
186 We declare the array of size 13
187 so that its highest element will be <TT>a[12]</TT>.
188 (We're wasting <TT>a[0]</TT> and <TT>a[1]</TT>;
189 this is no great loss.)
190 The variables <TT>d1</TT> and <TT>d2</TT> contain the rolls
191 of the two individual dice;
192 we add them together to decide which cell of the array to increment,
193 in the line
194 <pre>
195 a[d1 + d2] = a[d1 + d2] + 1;
196 </pre>
197 After 100 rolls, we print the array out.
198 Typically
199 (as craps players well know),
200 we'll see mostly 7's, and relatively few 2's and 12's.
201 </p><p>(By the way, it turns out that using the <TT>%</TT> operator
202 to reduce the range of the <TT>rand</TT> function
203 is <em>not</em> always a good idea.
204 We'll say more about this problem in an exercise.)
205 </p><p><a href="sx4aa.html" rel=subdocument>4.1.1 Array Initialization</a></p>
206 <p><a href="sx4ba.html" rel=subdocument>4.1.2 Arrays of Arrays (``Multidimensional'' Arrays)</a></p>
207 <hr>
209 Read sequentially:
210 <a href="sx4.html" rev=precedes>prev</a>
211 <a href="sx4aa.html" rel=precedes>next</a>
212 <a href="sx4.html" rev=subdocument>up</a>
213 <a href="top.html">top</a>
214 </p>
216 This page by <a href="http://www.eskimo.com/~scs/">Steve Summit</a>
217 // <a href="copyright.html">Copyright</a> 1995-1997
218 // <a href="mailto:scs@eskimo.com">mail feedback</a>
219 </p>
220 </body>
221 </html>