08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

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

Chapter 8 ■ Arrays

A better way is to use an array to store the 60 scores. We can think of this array as having

60 ‘locations’– we use one location to store one element, in this case, one score. To refer to a

particular score, we use a subscript. For example, if score is the name of the array, then score[5]

refers to the score in position 5 – here 5 is used as a subscript. It is written inside the square

brackets, [ and ].

In general, an array can be used to store a list of values of the same type; for instance, we

speak of an array of integers, an array of characters, an array of strings, or an array of floatingpoint

numbers. As you will see, using an array allows us to work with a list in a simple, systematic

way, regardless of its size. We can process all or some items using a simple loop. We can also do

things like search for an item in the list or sort the list in ascending or descending order.

8.2 Array Declaration

Before an array is used, it must be declared. For example, consider the statement:

int score[60];

This declares that score is an ‘integer array’ or an ‘array of ints’ with subscripts ranging from

0 to 59. An array declaration consists of

• The type (int, in this example)

• The name of the array (score, in this example)

• A left square bracket, [

• The size of the array (60, in this example)

• A right square bracket, ]

In C, array subscripts start at 0 and go up to n-1, if n is the size of the array.

We can think of the declaration as creating 60 int variables that can be referred to collectively

by the array variable score. To refer to a specific one of these scores, we use a subscript written in

square brackets after the array name. In this example,

score[0] refers to the 1st score

score[1] refers to the 2nd score

score[2] refers to the 3rd score

.

.

score[58] refers to the 59th score

score[59] refers to the 60th score

As you can see, array subscripting is a bit awkward in C; it would be much nicer (and logical)

if score[i] were to refer to the ith score. We will see how to get around this shortly.

It is an error to try to refer to an element that is outside the range of subscripts allowed. If you

do, you will get an “array subscript” error. For example, you cannot refer to score[60], score[-1]

and score[99] since they do not exist.

A subscript can be written using a constant (like 25), a variable (like n), or an expression

(like i+1). The value of the subscript determines which element is being referred to.

198

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!