Introduction to Arrays ---------------------- The declarations such as these char a; int counter; float price; only store one value. The variables are called scalar variables since they only store one value. Arrays allow you to store multiple values in one variable. The simplest type of array is a single dimensional array. There are also higher dimensional arrays such as double, triple, etc... Single Dimensional Array ------------------------ A single dimensional array is also called a one-dimensional array. These arrays are defined as follows: data_type variable_name[size] The data_type may be any one of the standard data types such as int and float or a more complicated data type. The variable_name follows the standard rules for scalar variables. The size is the number of elements in the array or list. Here are some example one-dimensional array declarations: char code[4]; /* array of 4 character codes */ double price[6]; /* array of 6 double precision prices */ float amount[100]; /* array of 100 floating point amounts */ The array code[4] looks like this in memory: |__|__|__|__| where each cell is a character (1 byte long). The array price[6] would look like this in memory: |________________|________________| ... |________________| 1 2 6 where each element is 8 bytes long (in UNIX doubles are usually 8 bytes). An index is used to access each element of the array: code[0] accesses the first element of code code[1] accesses the 2nd element of code code[2] accesses the 3rd element of code code[3] accesses the 4th element of code Sample Assignments ------------------ char a[3]; a[0] = 'a'; a[1] = 'b'; a[2] = a[1]; ----------- float bell[4]; float val = 5; bell[2] = 0.1; bell[3] = bell[2] + val; ----------- int more[10]; int i; i = 2; more[2*i] = 13; /* note the expression as the index */ more[3-i] = -10; more[9] = more[2*i] * more[1] - 10; Looped Assignments ------------------ int numbers[5]; int i; for(i=0;i<5;i++) numbers[i] = i*2; This loop will assign the values 0, 2, 4, 6, 8 to the array elements numbers[0], numbers[1], numbers[2], numbers[3] and numbers[4] respectively. Example to Add and Multiply Array Elements ------------------------------------------------- float values[4]; int i; int sum = 0; /* Additive identity */ int product = 1; /* Multiplicative identity */ /* assign values 3+i to array */ for(i=0;i<4;i++) values[i] = 3 + i; /* 3, 4, 5, 6 */ /* compute sum of all elements */ for(i=0;i<4;i++) sum += values[i]; /* compute product of all elements */ for(i=0;i<4;i++) product *= values[i]; Example Program 7-1 from the book ------------------------------- #include main() { int i, grades[5]; for(i = 0;i<=4;i++) { printf("Enter a grade: "); scanf("%d", &grades[i]); } for(i = 0;i<=4;i++) { printf("\ngrades %d is %d",i,grades[i]); } } This program simply reads in 5 grades and prints them back. Array Initialization -------------------- Arrays may be initialized as part of their declaration as follows: data_type variable_name[size] = {element1,element2, .. ,element_size}; Examples are: float a[5] = {1.1, 2.2, 3.3, 4.4, 5.5}; int barrel[3] = {1, 5, -7}; char apple[4] = {'o', 'n', 'c', 'e'}; A special form of the array initialization for characters is as follows: char str[] = "some string goes here"; This will automatically assign to the variable "str" the sequence of characters 's','o', ... ,'c','e' and then in addition '\0' which is the null character. The null is necessary for strings. The C compiler uses the null character as the termination of the string. Here is a sample program illustrating the use of array initializers: #include main() { int a[3] = {1,2,3}; float b[4] = {1.1, 2.2, 3.3, 15.6}; char c[4] = {'h','i','!','!'}; char d[] = "dill weed"; printf("%d %d %d\n",a[0],a[1],a[2]); printf("%f %f %f %f\n",b[0],b[1],b[2],b[3]); printf("%c%c%c%c\n",c[0],c[1],c[2],c[3]); printf("%s\n",c); printf("%s\n",d); } A sample run: %prog_7 1 2 3 1.100000 2.200000 3.300000 15.600000 hi!! hi!!?ŒÌÍ@ ÌÍ@S33Ay™š dill weed Notice that the fourth printf() statement prints "hi!!" plus a bunch of garbage that continues on the next line and further. This illustrates the unpredictability of a string not being terminated by a null character '\0'. Strings ------- Strings are arrays of the basic char data type. A sample declaration for a string is as follows: char str[10]; This is a one-dimensional array called str of size 10 that is of type char. This may also be referred to as a string. When printing strings, as shown above, use the '%s" qualifier. For example: printf("The string is %s\n", str); This will display the message along with the string str. The initialization of strings is done as follows: char str[] = "hi there"; Input of Strings ---------------- One way to input strings is using the scanf() function. Here is a sample program. #include main() { char str[10]; printf("Enter a string: "); scanf("%s", str); /* note no & sign needed for arrays */ printf("The string is %s\n", str); } This outputs for an input of "hi there": Enter a string: hi there The string is hi Why does it only print the "hi" part of the string? The reason is that scanf() uses spaces as delimiters and that includes strings. So when the space was encountered in "hi there" it thought the end of the string was reached. A better way to read in strings is by use of the command: gets(string_to_read); This command reads in a whole string. Look at this example program: #include main() { char str[10]; printf("Enter a string: "); gets(str); printf("The string is %s\n", str); } The output is for input string "hi there": Enter a string: hi there The string is hi there This program may also be modified to use another command called: puts(string_to_output); This will display a string to the screen. The printf() has more flexibility for displaying the string, but the puts command may also be used. Here is the modified program: #include main() { char str[10]; printf("Enter a string: "); gets(str); printf("The string is "); puts(str); } The output for input string "hi there" is: Enter a string: hi there The string is hi there Be careful about not using more characters than you have specified for the string length. C, in general, is sloppy and will let you get away with using more characters than declared. However, the results for operations on these strings is unpredictable. It may work one minute, but not the next.