You are on page 1of 14

ARRAYS CHAPTER 6

Objective: Having completed this chapter the student should be able:

- to define single and two dimensional arrays


- to declare and initialize arrays

6.1 What is an array?

- An array is a collection of variables which are all of the same type. It is a


grouping of the same data type and referred to by the same name.

- The complete set of values is referred to as an array while the individual


values are called elements. In its simplest form, an array can represent a list
of numbers.

- In C, arrays are indicated with brackets containing a positive integer constant.

Arrays can be use to denote the x and y coordinates of a number of data points.
In this case, we have two dimensional arrays, one for x and another for y.

6.2 Declaration of Arrays

Arrays must be declared and defined before they can be used in a program. Array
declaration tell the compiler the name of the array, the type of each element, and
the size or number of elements in the array. In general, the syntax for a 1-D
array declaration is

type array_name[array_size];

type specifies the type of element that will be contained in the array,
such as int, float, or char.
array_size Indicates the maximum number of array elements that can be
stored inside the array. Array size must be declared with a
constant.

Example 1: int days[7];

declares an array named days that is type int and has 7 elements. The individual
elements are referred to by subscript as day[0] through day[6].

86
Example 2: The array int x[6];

contains the following elements:

x[0],x[1],x[2],x[3],x[4] and x[5].

One dimensional arrays (1-D arrays)

One dimensional array is an array that has only a single subscript. A subscript is
used to identify the individual elements in the array

float marks[7];

array_size
array_ name
array type

Individual array elements are stored in sequential memory location as illustrated


below
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6]

Note that the first array element is marks[0].

For example, we want to represent a set of six numbers, say ( 27, 30,15,35,32,20)
by an array variable number. Then, we decalare the variable number as follows:

int number[6];

The values to the array elements can be assigned as follows:

number[0]=27;
number[1]=30;
number[2]=15;
number[3]=35;
number[4]=32;
number[5]=20;

6.3 Initialization of Arrays

After an array is declared, its elements must be initialized. Array initilization can
be full or partial.

Example 3: Initialization without size

87
int numbers[ ] = {2, 6, 11, 23, 30};

2 6 11 23 30

Example 4: Partial initialization

int numbers[5]={2, 6};

2 6 0 0 0

Example 5: for (i = 0; i < 100;i++)


salary[ i ] = 0.0;

The for statement initializes all the 100 elements of the array to 0.0.

Example 6: int score [5] = {66, 89, 75, 100, 50};

The array declaration will create an array of five elements such that

score [0] is initialized to 66


score [1] is initialized to 89
score [2] is initialized to 75
score [3] is initialized to 100
score [4] is initialized to 50

The general form of initialization of array is:

type array_name[array_size] = {list of values};

Only fixed-length arrays can be initialized when they are defined. Variable-
length arrays must be initialized by inputting or assigning the values.

Example 7: int numbers[5]={2, 6, 11, 23, 30};

2 6 11 23 30

Example 8:

(a) int number[3] = {0,0,0};

(b) int array[4] = { 20, 30, 40,50 };

assigns the value 20 to array[0], 30 to array[1], 40 to array[2] and 50


to array[3]

88
Example 9: Let m be the array shown in Table 6.1.

m[0] m[1] m[2] m[3] m[4] m[5] m[6] m[7]

18.0 14.0 8.0 10.0 4.5 14.0 16.0 20.0

Table 6.1 : Array m

From Table 6.1:

Statement Explanation
printf(“ %.1f ”,m[0]); Display the value of m[0], which is 18.0
m[3] = 15.0; Stores the value 15.0 in m[3]
sum = m[0] + m[1] Stores the sum of m[0] and m[1], which is 32.0 in the
variable sum
sum += m[2]; Adds m[2] to sum. The new sum is 40.0
m[3] += 2.0; Adds 2.0 to m[3]. The new m[3] is 17.0
m[2] = m[0] + m[1] Stores the sum of m[0] and m[1] in m[2].
The new m[2] is 32.0

6.4 Array subscript

A subscript is used to differentiate between the individual array elements and to


specify which array element to be manipulated.

Example 10: From table 6.1, the subscript variable m[i] referred to a particular
element of the array. If i has the value 0, then the subscript value is
0, and m[0] is referenced assume the variable i is assumed to be of
type int with value 4.

Statement Explanation
i = 4;
printf( “ %d %.1f ”, 3, m[3] ); Display 3 and 10.0 (the value of m[3])
printf( “ %d %.1f ”, i, m[ i ] ); Display 4 and 4.5 (the value of m[4])
printf( “ %.1f ”, m[ i ] + 1 ); Display 5.5 (the value of m[4] plus 1)
printf( “ %.1f ”, m[ i + i] ); Invalid.
printf( “ %.1f ”, m[ 2 * i] ); Invalid
m[ i ] = m[ i + 1]; Assigns 14.0 (value of m[5]) to m[4]
m[ i - 1] = m[ i ]; Assigns 4.5 (value m[4] ) to m[3]
m[ i ] - 1= m[ i ]; Illegal assignment statement

Example 11: Calculate the slope for many different pairs of points, given the
slope, m1 , of a line connecting two points, ( x1,y1 ) and
( x 2 ,y2 ) .

89
Answer: The slope of the line connecting the two points is given by

y -y
m1 = 2 1
x 2 -x1

In C, this can be written as an assignment statement:

m[1] = (y[2] – y[1]) / (x[2] – x [1]);

Therefore, to calculate the slope all the slopes of the lines connecting all 100 data
points, we put the array in a loop, such as

for (i=0; i<99; i++)


{
m [i ] = ( y [i+1] -y [i ]) ( x [i+1] -x [i ]) ;
}

Example 12: Program using for loops to process arrays.

#include <stdio.h>
#define hours_size 10

main()
{
double hours[hours_size];
int i;

/* Set all array elements to 0 */


for (i = 0; i < hours_size; i++)
hours[ i ] = 0;

/* sets array elements to 0, 10, 20, ... */


for (i = 0; i < hours_size; i++)
hours[ i ] = 10 * i;

/* sets array elements to 20, 25, 30, ... */


hours[0] = 20;
for (i = 1; i < hours_size; i++)
hours[i] = hours[i-1] + 5;

/* print the array subscripts and element values */


printf("%s %s\n", "i", "hours[ i ]");
for (i = 0; i < hours_size; i++)
printf("%d %f\n", i, hours[ i ]);

90
Sample program output:

i hours[ i ]
0 20.000000
1 25.000000
2 30.000000
3 35.000000
4 40.000000
5 45.000000
6 50.000000
7 55.000000
8 60.000000
9 65.000000

Example 13: Program to read data into an array: Read the values one at a time.

1 #include <stdio.h>
2 #define hours_size 5
3 main()
4 {
5 double hours[hours_size];
6 int i;
7 for ( i = 0; i < hours_size; i++)
8 {
9 printf("Enter value for hours[%d]: ", i);
10 scanf("%d", &hours[ i ]);
11 }
12 }

Sample program output:

Enter value for hours[0]: 10


Enter value for hours[1]: 8
Enter value for hours[2]: 16
Enter value for hours[3]: 5
Enter value for hours[4]: 50

Example:

/* Example: arrays */

1 #include <stdio.h>
3 main()
4 {
5 int u;
6 long p2[21] = { 1, 2, 4, 8, 16, 32, 64, 128,
7 256, 512, 1024, 2048, 4096,
8 8192, 16384, 32768, 65536,

91
9 131072, 262144, 524288,
10 1048576
11 };
12 for (u = 0; u < 21; u++)
printf("2 to the power %2i = %7li\n", u, p2[u]);
}

Sample program output:

2 to the power 0 = 1
2 to the power 1 = 2
2 to the power 2 = 4
2 to the power 3 = 8
2 to the power 4 = 16
2 to the power 5 = 32
2 to the power 6 = 64
2 to the power 7 = 128
2 to the power 8 = 256
2 to the power 9 = 512
2 to the power 10 = 1024
2 to the power 11 = 2048
2 to the power 12 = 4096
2 to the power 13 = 8192
2 to the power 14 = 16384
2 to the power 15 = 32768
2 to the power 16 = 65536
2 to the power 17 = 131072
2 to the power 18 = 262144
2 to the power 19 = 524288
2 to the power 20 = 1048576

6.5 Two-dimensional array

A structure for storing multiple values of the same type organized by rows and
columns:

int test_scores[200][2];

Suppose it is a collection of test scores for a class of 200 students who took 2
exams. Scores for 5th student would be stored as:

test_scores[4][0], test_scores[4][1], test_scores[4][2],

92
Often there is a need to store and manipulate two dimensional data structure
such as matrices and tables. In this case, the array has two subscripts. One
subscript denotes the row and the other the column.

The declaration of two dimension arrays is as follows:

type array_name[row_size][column_size];

Example 14: int m[10][20]

Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20


columns(numbered 0 through 19). The first element of the matrix is m[0][0] and
the last row last column is m[9][19]

6.6 Initialization of two dimensional arrays

Like the one dimension arrays, 2 dimension arrays may be initialized by following
their declaration with a list of initial values enclosed in braces

Example 15: int table[2][3]={0,0,01,1,1};

Initializes the elements of first row to zero and second row to 1. The initialization
is done row by row. The above statement can be equivalently written as

int table[2][3]={{0,0,0},{1,1,1}}

Example 16: Initialize array with square of index and then prints the array..

Answer:

1 #include <stdio.h>
2 #define array_size 10
3 main()
4 {
5 int i;
6 int sqr_array[array_size];
7 for( i=0; i<array_size; i++ )
8 sqr_array[ i ]=i*i;
9 printf(“Element\t\tSquare\n”);
10 printf(“_______\t\t_______\n”);
11 for( i=0; i<array_size; i++ )
12 printf( “ %4d\t\t%3d\n”,i,sqr_array[ i ] );
13 }
Sample program output:

Element Square
_______ _______

93
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81

An example program

1. The following program will use arrays to keep track of grades in a class.

#include <stdio.h>
#include <math.h>
#define NUM_STU 5 /* 5 students in the class */

/* Two arrays, one for student id, and one for student grade */

int student_id[NUM_STU] = {123, 223, 326, 117, 326};


int student_gr[NUM_STU] = {84, 74, 90, 100, 70};

main()
{

int i, hi, lo, sum;


double avg;

hi = student_gr[0];
lo = student_gr[0];
sum = 0;

/* print the grades to the screen */

printf("id\tgrade\n");

for (i = 0; i < NUM_STU; i++) {

printf("%d\t%d\n",student_id[i], student_gr[i]);

if(hi < student_gr[i])


hi = student_gr[i];

if(lo > student_gr[i])


lo = student_gr[i];

sum += student_gr[i];

94
}

printf("\nThe highest grade: %d", hi);


printf("\nThe lowest grade: %d", lo);
printf("\nThe sum of the grades: %d", sum);

avg = sum / NUM_STU;


printf("\nThe average grade: %f\n\n", avg);

Sample output of this program:

id grade
123 84
223 74
326 90
117 100
326 70

The highest grade: 100


The lowest grade: 70
The sum of the grades: 418
The average grade: 83.000000

/* Example: matrices represented by 2-dimensional arrays */

1 #include <stdio.h>
2 main()
3 {
4 int A[3][3] = {{2, 4, 6}, {0, -1, 3}, {5, 2, -1}};
5 int B[3][3] = {{1, 3, -2}, {3, 0, 2}, {1, -3, 4}};
6 int C[3][3];
7 int i, j, k;
8
9 printf("A = [%3i %3i %3i ]\n", A[0][0], A[0][1], A[0][2]);
10 printf(" [%3i %3i %3i ]\n", A[1][0], A[1][1], A[1][2]);
11 printf(" [%3i %3i %3i ]\n\n", A[2][0], A[2][1], A[2][2]);
12
13 printf("B = [%3i %3i %3i ]\n", B[0][0], B[0][1], B[0][2]);
14 printf(" [%3i %3i %3i ]\n", B[1][0], B[1][1], B[1][2]);
15 printf(" [%3i %3i %3i ]\n\n", B[2][0], B[2][1], B[2][2]);
16
/* multiply C = A.B: */

17 for (i = 0; i < 3; i++)


18 for (j = 0; j < 3; j++)

95
19 {
20 C[i][j] = 0;
21 for (k =0; k < 3; k++)
22 C[i][j] += A[i][k] * B[k][j];
23 }
23 printf("A.B = [%3i %3i %3i ]\n", C[0][0], C[0][1], C[0][2]);
25 printf(" [%3i %3i %3i ]\n", C[1][0], C[1][1], C[1][2]);
26 printf(" [%3i %3i %3i ]\n\n", C[2][0], C[2][1], C[2][2]);
27
/* multiply C = B.A: */

28 for (i = 0; i < 3; i++)


29 for (j = 0; j < 3; j++)
30 {
31 C[i][j] = 0;
32 for (k =0; k < 3; k++)
33 C[i][j] += B[i][k] * A[k][j];
34 }
35
36 printf("B.A = [%3i %3i %3i ]\n", C[0][0], C[0][1], C[0][2]);
37 printf(" [%3i %3i %3i ]\n", C[1][0], C[1][1], C[1][2]);
38 printf(" [%3i %3i %3i ]\n\n", C[2][0], C[2][1], C[2][2]);
39 }

Sample output of this program:

A =[ 2 4 6]
[ 0 -1 3 ]
[ 5 2 -1 ]

B = [ 1 3 -2 ]
[ 3 0 2]
[ 1 -3 4 ]

A.B = [ 20 -12 28 ]
[ 0 -9 10 ]
[ 10 18 -10 ]

B.A = [ -8 -3 17 ]
[ 16 16 16 ]
[ 22 15 -7 ]

96
6.7 Strings

In C, a string is simply an array of type char.

Declaring a string:

char str_var[20];

The above declaration creates a variable that can hold a string from 0 to 19
characters long.

Initializing a string:

char str_var[20] = "Text goes here";

The above creates the following in memory:

Text g o e s h e r e \0 ? ? ? ? ?

- The '\0' is a null character, and indicates the end of the string. The content
following the null character is ignored by the string functions in C.
- Note: the assignment operator (=) can be used for initialization of a string, but
it CANNOT be used to change the value of an existing string. This should be
accomplished using the strcpy function, listed below.

Arrays of strings

- An array of strings can be a two dimensional array of characters where each


row is one string.

Below is an array of the days of the week:

char days_week[7][10] = {"Monday", "Tuesday", "Wednesday", Thursday",


"Friday", "Saturday", "Sunday"};

Such an array can hold 7 strings, each up to 9 characters long.

printf and scanf with strings

- printf recognizes strings with the use of the %s argument.


- To right-justify, place the minimum field width in the argument, such as %9s.
- To left-justify, add a "-", such as %-9s.

Example 17:

printf("__%-10s__%10s__\n","Text", "Text2");

97
Results:

__Text __ Text2__

- With scanf, the %s argument is also used.


- With a string, no "&" is used.

Example 18:
char astring[20];
int numb;

scanf("%s", astring);
scanf("%d", &numb);

Library functions for strings

Function Library Description


strcpy(s1, s2) string.h Copies the value of s2 into s1
strncpy(s1, s2, n) string.h Copies n characters of s2 into s1. Does not add a null.
strcat(s1, s2) string.h Appends s2 to the end of s1
strncat(s1, s2, n) string.h Appends n characters of s2 onto the end of s1
Compared s1 and s2 alphabetically; returns a negative
strcmp(s1, s2) string.h value if s1 should be first, a zero if they are equal,
or a positive value if s2 sbould be first
Compares the first n characters of s1 and s2 in the
strncmp(s1, s2) string.h
same manner as strcmp
Returns the number of characters in s1 not counting
strlen(s1) string.h
the null

- strncpy can be used to extract substrings that begin in the middle of a string
as well as the beginning.
- To do this, the s2 argument must be the specific memory address in which to
begin copying.

Example 19:

char lastname[20];
char name[10] = "Joe Bob";

/* extract the last name into "lastname" */

strncpy(lastname, &name[4], 3);

98
lastname[3] = '\0';

EXERCISE
1. True or false:
Let y be defined as int y[100];
a. valid array elements are y[0],y[1],…,y[99]
b. valid array elements are y[0],y[1],…,y[100]
c. none of the above

2. True or false

a. All elements of a given array have the same data type


b. The subscript of the first element of a one dimensional array is 1.
c. If an array has 49 elements, the size of an array is 50.
d. Arrays can be used to store lists.
e. If an array x has n elements, then the first element is x[0] and the
last element is x[n-1].
f. If x is an array with type int elements, then the statement
x += 5;
adds 5 to each elemt of x.
g. If x is an array with type int elements and the value of x[4] is 3, then
the ststement

printf(“%d\n”,x[x[4]-1]);

prints one less than the value of x[3].

3. Find the error(s) if any, in each of these statements:

a. int m, n(4);
b. double temperature[-200];
c. float x12y[66], 2mn[33];

Answer:

int m, n[4];
double temperature[200]; must be >0
float x12y[66], mn2[33];

99

You might also like