20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

98 Chapter 7 Work<strong>in</strong>g with Arrays<br />

values [0]<br />

values [1]<br />

values [2]<br />

values [3]<br />

values [4]<br />

values [5]<br />

values [6]<br />

values [7]<br />

values [8]<br />

values [9]<br />

Figure 7.1<br />

The array values <strong>in</strong> memory.<br />

The elements of arrays declared to be of type <strong>in</strong>t, float, or char can be manipulated <strong>in</strong><br />

the same fashion as ord<strong>in</strong>ary variables.You can assign values to them, display their values,<br />

add to them, subtract from them, and so on. So, if the follow<strong>in</strong>g statements appear <strong>in</strong> a<br />

program, the array values would conta<strong>in</strong> the numbers as shown <strong>in</strong> Figure 7.2.<br />

<strong>in</strong>t values[10];<br />

values[0] = 197;<br />

values[2] = -100;<br />

values[5] = 350;<br />

values[3] = values[0] + values[5];<br />

values[9] = values[5] / 10;<br />

--values[2];<br />

The first assignment statement has the effect of stor<strong>in</strong>g the value 197 <strong>in</strong> values[0]. In a<br />

similar fashion, the second and third assignment statements store –100 and 350 <strong>in</strong>to<br />

values[2] and values[5],respectively.The next statement adds the contents of<br />

values[0] (which is 197) to the contents of values[5] (which is 350) and stores the<br />

result of 547 <strong>in</strong> values[3]. In the follow<strong>in</strong>g program statement, 350—the value conta<strong>in</strong>ed<br />

<strong>in</strong> values[5]—is divided by 10 and the result is stored <strong>in</strong> values[9].The last<br />

statement decrements the contents of values[2], which has the effect of chang<strong>in</strong>g its<br />

value from –100 to –101.<br />

The preced<strong>in</strong>g program statements are <strong>in</strong>corporated <strong>in</strong>to Program 7.1.The for loop<br />

sequences through each element of the array, display<strong>in</strong>g its value at the term<strong>in</strong>al <strong>in</strong> turn.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!