ONE-DIMENSIONAL ARRAYS




One Dimensional Arrays

Authored by: Lex Jacobsen and John Even

Faculty Supervisor: Al Day

Some material derived from lessons authored by Dr. Larry Genalo

HTML documentation by: Julie Sandberg

Date last updated: 7/24/96


Introduction

Subscripted Variable Name: A C variable name common to many variables

Subscripted Array: A systematic diagrammatical representation of a subscripted variable

In general they are multidimensional


Sample Picture





















Subscripted Variable Rules

  1. Subscripted variables can be double, integer, or character.

  2. The maximum number of subscripts is dictated by the compiler vendor. Twelve is common. Six is the minimum for ANSI standards.

  3. Arithmetic expressions may be used for subscripts.

  4. Subscripts must be integer valued.

  5. A statement must be included in your program which sets aside storage space (dimensions) for your arrays.

Declaring Arrays

NOTE: Arrays are declared with the other variables in the program.


Reading Arrays with a for loop





	double x[5]
	FILE *inp;
	inp = fopen("input.dat", "r");
	for (n = 0; n < 5; ++n)
   	   fscanf(inp, "%lf", &x[n]);
	fclose(inp);









Writing Arrays with a for loop





	double x[5];
	FILE *outp;
 	outp = fopen ("OUT.DAT","w");
	for (n = 0; n < 5; ++n)
 	   fprintf(outp, "%10.4 f\n", x[n]);
	fclose (outp);






NOTE: Produces a column of output because of the newline character in the format specification


Example

A program to find the largest number in a list


This program sets the variable big to the first element in the list. It then iterates through the list replacing big with any larger numbers that it comes across. When the end is reached, big holds the value of the largest number in the list.










#include < stdio.h >
int main(void) {
    double x[100], big;
    int j=1, i;
    inp = fopen("IN.DAT", "r")
    for (j=0; j < 100; ++j)
        fscanf (inp, "%lf", & x[j]);
    big = x[0];
    for (i = 1; i < 100; ++i)
        if (x[i] > big) big = x[i];
    printf("LARGEST VALUE = %f/n", big);
    fclose(inp);
    return (0);
}

How can this program be modified so that the array is placed in order? i.e. The largest array element becomes x[0], the second largest becomes x[1], etc.



Function Rules

When using a function:


One-Dimensional Example

If an array is to be used in a function as an input argument only, the type qualifier const can be used. Since the array is used only for input, the compiler doesn't need to make a copy or know the size. It can use the original.