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

In this chapter, we will explain the following:

• What is an array and how to declare one

• How to store values in an array

• How to read a known number of values into an array using a for loop

• How to process elements of an array using a for loop

• How to read an unknown number of values into an array using a while loop

• How to extract a required element from an array with a subscript

• How to find the sum of numbers stored in an array

• How to find the average of numbers stored in an array

• How to use an array to keep several counts

• How to work with a string as an array of characters

• How to reverse the elements in an array

• How to write a function to tell if a phrase is a palindrome

• How to pass an array as an argument to a function

• How to find the largest and smallest values in an array

8.1 Simple vs Array Variable

The variables we have been using so far (such as ch, n, sum) are normally called simple variables.

At any given time, a simple variable can be used to store one item of data: for instance, one

number or one character. Of course, the value stored in the variable can be changed, if we wish.

However, there are many situations in which we wish to store a group of related items and to be

able to refer to them by a common name. The array variable allows us to do this.

For example, suppose we wish to store a list of 60 scores made by students in a test. We can

do this by inventing 60 different int variables and storing one score in one variable. But it would

be quite tedious, cumbersome, unwieldy, and timeconsuming to write code to manipulate these

60 variables. (Think of how you would assign values to these 60 variables.) And what if we needed

to deal with 200 scores?

197

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!