1 ICS103 Programming in C Lecture 12: Arrays I
2 Outline • What is an Array? • Declaring Arrays • Visual representation of an Array • Array Initialization • Array Subscripts • Accessing Array elements • Examples
3 What is an Array? • Scalar data types use a single memory cell to store a single value. • For many problems you need to group data items together. • A program that processes exam scores for a class, for example, would be easier to write if all the scores were stored in one area of memory and were able to be accessed as a group. • C allows a programmer to group such related data items together into a single composite data structure . • We now take a look at one such data structure: the Array . • An array is a collection of two or more adjacent memory cells that: Stores the same type of data values (e.g. int) Are referenced by the same name (i.e using one variable) • These individual cells are called array elements
4 Declaring Arrays • To declare an array, we must declare its name , type of data values it will store and the number of cells associated with it. Example: double x; • This instructs C to associate eight memory cells with the name x; these memory cells will be adjacent to each other in memory. • You can declare arrays along with regular variables double cactus, needle, pins; • It is a good practice to define the array size as constant: #define ARRAY_SIZE 12 int myArray[ARRAY_SIZE];
5 Declaring Arrays … • Each element of the array x may contain a single value of type double, so a total of eight such numbers may be stored and referenced using the array name x .
You've reached the end of your free preview.
Want to read all 14 pages?
- Spring '10
- Array, #include, #define, Array Array Initialization