Lecture 7 - Arrays & Strings
Lecture 7 - Arrays & Strings
Table of Contents
Introduction .................................................................................................................................................. 1
What Is An Array? ......................................................................................................................................... 1
Declaring Arrays ............................................................................................................................................ 2
Array Dimensions and types ......................................................................................................................... 3
Month 1 ........................................................................................................................................................ 3
Example ......................................................................................................................................................... 4
Initializing Arrays ........................................................................................................................................... 5
Example: Array that prints the number of days per month ..................................................................... 7
Here is the output ................................................................................................................................. 7
Explanation ................................................................................................................................................... 7
Example: Calculating the average of n numbers ...................................................................................... 8
Exercise ..................................................................................................................................................... 9
Example: Bubble sort ................................................................................................................................ 9
Example: Two – Dimensional array of scores ......................................................................................... 10
Strings ......................................................................................................................................................... 11
Example: Demonstrating string functions .............................................................................................. 14
Note:........................................................................................................................................................ 15
Revision Exercises ....................................................................................................................................... 15
Introduction
It is often necessary to store data items that have common characteristics in a form that supports
convenient access and processing e.g. a set of marks for a known number of students, a list of prices,
stock quantities, etc. Arrays provide this facility.
What Is An Array?
An array is a data structure that consists of a homogeneous ordered set of elements or a series of data
objects of the same type stored sequentially. That is to say that an array has the following
characteristics;
• Items share a name
• Items can be of any simple data type e.g. char, float, int, double.
• Individual elements are accessed using an integer index whose value ranges from 0 to the
value of the array size.
Illustration examples:
a. age
An array of 10 student ages (stored as integers)
22 19 20 21 21 22 23 10 19 20
b. letters
An array of 5 characters in an employee’s name
O K O T H
Declaring Arrays
An array definition comprises;
(i) Storage class (optional)
(ii) Data type
(iii) Array name
(iv) Arraysize expression (usually a positive integer or symbolic constant). This is enclosed in square
brackets.
Syntax:
Array_type array_name[maximum size];
Examples:
(i) Static char message[20]; A 20 character-type array called message. The individual
array values persist within function calls (static).
(iii) Because the array is declared as type float, each element can be assigned a float
value such as debts[5] = 32.54;
Other examples;
(iv) int emp_no[15]; /*An array to hold 15 integer employee numbers */
(v) char alpha [26]; /*an array to hold 26 characters */
An array’s dimension is the number of indices required to manipulate the elements of the array.
(i) A one-dimensional array requires a single index e.g. int numbers [10];
Resembles a single list of values and therefore requires a single index to vary between 0
to (array size -1).
(ii) Multi dimensional arrays
They are defined the same way as a one-dimensional array except that a separate pair of square
brackets is required for each subscript. Thus a two-dimensional array will require two pairs of
brackets, a three dimensional array will require three pairs of square brackets, etc.
An m by n two-dimensional array can be thought of as a table of values having m rows and n columns.
The number of elements can be known by the product of m (rows) and n(columns).
float table[50][50];
char page[24][80];
Static double records[100][60][255];
Example
Two-dimensional array representing sales ( ‘000 tonnes for a product in four months for five years).
Yr1 Yr2 Yr3 Yr4 Yr5
Month 1 23 21 27 23 22
Month 2 24 20 19 18 20
Month 3 26 23 26 29 24
Month 4 27 25 24 23 25
Automatic array
An automatic array is one defined inside a function including formal arguments. C allows us to initialise
automatic array variables as follows.
main()
{
Because the array is defined inside main, its an automatic array. The first element marks[0] is
assigned the value of 30 , marks[1] as 40 and so on.
External array
An external array is one defined outside a function.
They
(i) are known to all functions following them in a file e.g. from above, both main ( ) and feed ( ) can
use and modify the array SOWS.
(ii) Persist (retain values) as long as the program runs. Because they are not defined in any
particular function, they don’t expire when a particular function terminates.
----------
----------
int feed(int n)
{
---------
---------
Static array
A static array is local to the function in which it is declared but like an external array, it retains its values
between function calls and is inititialised to zero by default.
Example
Initializing Arrays
Like other types of variables, you can give the elements of arrays initial values. This is accomplished by
specifying a list of values the array elements will have. The general form of array initialisation for a one-
dimensional array is shown below.
The value list is a comma separated list of constants that are type compatible with the base
type of the array. The first constant will be placed in the first position of the array, the second
constant in the second position and so on. Note that a semi colon follows the }.
In the following example, a five – element integer array is initialised with the squares of the number 1
though 5.
This means that i[0] will have the value 1 and i[4] will have the value 25.
You can initialise character arrays in two ways. First, if the array is not holding a
null -terminated string, you simply specify each character using a comma separated list. For example,
this initialises a with the letters ‘A’, ‘B’, and ‘C’.
If the character array is going to hold a string, you can initialise the array using a quoted string, as
shown here.
Notice that no curly braces surround the string. They are not used in this form of initialisation. Because
strings in C must end with a null, you must make sure that the array you declare is long enough to
include the null. This is why name is 6 characters long, even though “Peter” is only 5 characters. When
a string constant is used, the compiler automatically supplies the null terminator.
For example, here the array sqr is initialised with the values 1 though 9, using row order.
int sqr [3][3] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
};
This initialisation causes sqr[0][0] to have the value 1, sqr[0][1] to contain 2, sqr[0][2] to contain 3,
and so forth.
If you are initialising a one-dimensional array, you need not specify the size of the array, simply put
nothing inside the square brackets. If you don’t specify the size, the compiler simply counts the number
of initialisation constants and uses that that value as the size of the array.
For example int p[] = {1,2,4,8,16,32,64,128}; causes the compiler to create an initialised array eight
elements long.
Arrays that don’t have their dimensions explicitly specified are called unsized arrays. An unsized array is
useful because it is easier for you to change the size of the initialisation list without having to count it
and then change the array dimension dimension. This helps avoid counting errors on long lists, which is
especially important when initialising strings.
If at a later date, you wanted to change the prompt to “Enter your last name: “ , you would not have to
count the characters and then change the array size.
For multi dimensional arrays, you must specify all but the left dimension to allow C to index the array
properly. In this way you may build tables of varying lengths with the compiler allocating enough storage
for them automatically.
For example, the declaration of sqr as an unsized array is shown here.
int sqr[][3] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
};
The advantage to this declaration over the sized version is that tables may be lengthened or shortened
without changing the array dimensions.
#include<stdio.h>
#define MONTHS 12
int days [MONTHS] = {31,28,31,30,31,30,31,31,30,31,30,31};
main()
{
int index;
extern int days[ ];
for (index=0; index <MONTHS; index + + )
printf( “Month %d has %d days. \n ”, index+1, days [index]);
return 0;
}
Explanation
• By defining days [ ] outside the function, we make it external. We initialise it with a list
enclosed in braces, commas are used to separate the members of the list.
• Inside the function the optional declaration extern int days [ ]; uses the keyword extern to
remind us that days array is defined elsewhere in the program as an external array. Because it
is defined elsewhere we need not give its size here. (ommitting it has no effect on how the
program works)
Note:
The number of items in the list should match the size of the array.
Processing an array
Single operations which involve entire arrays are not permitted in C. Operations such as
assignment, comparison operators, sorting etc must be carried out on an element-by-element
basis. This is usually accomplished within a loop where each pass through the loop is used to
process one array element. The number of passes through the loops will therefore be equal to
the number of array elements to be processed.
Example: Calculating the average of n numbers
#include<stdio.h>
main()
{
int n, count;
float avg, d, sum =0.0;
float list[100];
/* Read in a value of n */
printf(“ \n How many numbers will be averaged ? “);
scanf(“ %d “, &n);
printf(“ \n”);
/* Read in the numbers */
for (count = 0; count < n; count++)
{
printf(“ i = %d x = ”, count+1);
scanf(“ %f “, &list[count]);
sum+=list[count];
}
The average is 2
Exercise
Assuming that the number of values in the list is already known to be 3, and that the list values
are 5, 6, 8, rewrite the above program without having to request input from the keyboard.
Arrays are especially useful when you want to sort information. For example, this program lets
the user enter up to 100 numbers and then sorts them. The sorting algorithm is the bubble
sort. The general concept of the bubble sort is the repeated comparisons and, if necessary
exchanges of adjacent elements. This is a little, like bubbles in a tank of water with each bubble,
in turn, seeking its own level.
#include<stdio.h>
main()
{
int item[100];
int a, b, t;
int count;
/ * Read in the numbers */
printf(“ How many numbers? “);
scanf(“ %d “, &count);
for (a = 0; a < count; a ++)
scanf(“ %d”, &item[a]);
/* Now sort them using a bubble sort */
for(a = 1; a < count; + + a)
for(b = count –1; b > =a; - - b)
{
/* Compare adjacent items */
if (item[b –1] > item[b])
/* exchange the elements */
{
t = item[b – 1];
item[b –1] = item[b];
item[b] = t;
}
}
/* Display sorted list */
for(t = 0; t < count; t++)
printf(“ %d “, item[t]);
return 0;
}
#include<stdio.h>
#define STUDENT 5 /* Set maximum number of students */
#define CATS 4 /* Set maximum number of cats */
main()
{
/* Declare and initialize required variables and array */
int rows, cols, SCORES[STUDENT][CATS];
float cats_sum , stud_average, total_sum=0.0, average;
printf(“Entering the marks ...............\n\n”);
/* Read in scores into the array */
for(rows=0;rows<STUDENT; rows++) /* Outer student loop */
{
printf(“\n Student % d\n”, rows+1);
cats_sum=0.0; /* Initializes sum of a student’s marks */
for(cols=0;cols<CATS;cols++) /* Inner loop for cats */
{
printf(“CAT %d\n”,cols+1);
scanf(“ %d”, &SCORES[rows][cols]);
cats_sum + =SCORES[rows][cols]; /* Adjust sum of marks */
}
stud_average=cats_sum/CATS; /*Calculate the average of each student */
printf(“\n Total marks for student %d is %3.2f “,rows+1, cats_sum);
printf(“\n Average score for the student is %3.2f “,stud_average);
total_sum+=cats_sum; /* Adjust the class total marks */
}
average=total_sum/(STUDENT*CATS); /* Compute the class average */
printf(“\n Total sum of marks for the class is %3.2f\n “, total_sum);
printf(“\n The class average is %3.2f\n “,average);
/*Printing the array elements */
for(rows=0;rows<STUDENT; rows++)
for(cols=0;cols<CATS;cols++)
{
printf(“\n Student %d, Cat %d “,rows+1, cols+1);
printf(“\n\t %d \n”, SCORES[rows][cols]);
}
return 0;
}
Strings
In C, one or more characters enclosed between double quotes is called a string. C has no built-in string
data type. Instead, C supports strings using one dimensional character arrays. A string is defined as a
null terminated character array. In C, a null is 0. This fact means that you must define the array is going
to hold a string to be one byte larger then the largest string it is going to hold, to make room for the null.
To read a string from the keyboard you must use another of C’s standard library functions, gets( ),
which requires the STDIO.H header file. To use gets( ), call it using the name of a character array
without any index. The gets( ) function reads characters until you press <ENTER>. The carriage return is
not stored, but it is replaced by a null, which terminates the string. For example, this program reads and
writes a string entered at the keyboard.
#include<stdio.h>
main()
{
char str[80];
int i;
printf( “ Enter a string (less than 80 characters): \n”);
gets(str);
for( i = 0 ; str[i]; i++)
printf(“ %c”, str[i]);
return 0;
}
The gets( ) function performs no bounds checking, so it is possible for the user to enter more characters
that gets( ) is called with can hold. Therefore be sure to call it with an array large enough to hold the
expected input.
In the previous program, the string that was entered by the user was output to the screen a character at
a time. There is however a much easier way to display a string, using printf( ). Here is the previous
program rewritten..
#include<stdio.h>
main()
{
char str[80];
printf( “ Enter a string (less than 80 characters): \n”);
gets(str);
printf(str);
return 0;
}
If you wanted to output a new line, you could output str like this:
This method uses the %s format specifier followed by the new line character and uses the array as a
second argument to be matched by the %s specifier.
The C standard library supplies many string-related functions. The four most important are strcpy( ),
strcat( ), strcmp( ) and strlen( ). These functions require the header file STRING.H.
It copies the contents of from to to. The contents of from are unchanged. For example, this fragment
copies the string “hello’ into str and displays it on the screen.
char str[80];
strcpy(str, “hello”);
printf(“%s”, str);
The strcpy( ) function performs no bounds checking, so you just make sure that the array on the
receiving end is large enough to hold what is being copied, including the null terminator.
The strcat( ) function adds the contents of one string to another. This is called concatenation. Its general
form is
It adds the contents of from to to. It performs no bounds checking, so you must make sure to is large
enough to hold its current contents plus what it will be receiving. This fragment displays hello there.
char str[80];
strcpy(str, “hello”);
strcat(str, “there”);
printf(str);
The strcmp( ) function compares two strings. It takes this general form.
strcmp(s1, s2);
It returns 0 if the strings are the same. It returns less than 0 if s1 is less than s2 and greater than 0 if s1 is
greater than s2. The strings are compared lexicographically; that is in dictionary order. Therefore, a
string is less than another when it would appear before the other in a dictionary. A string is greater than
another when it would appear after the other. The comparison is not based upon the length of the
string. Also, the comparison is case-sensitive, lowercase characters being greater than uppercase. This
fragment prints 0, because the strings are the same.
The strlen( ) function returns the length , in characters, of a string. Its general form is
strlen(str);
#include<string.h>
#include<stdio.h>
main()
{
char str1[80], str2[80];
int i;
printf(“ Enter the first string: “);
gets(str1);
printf(“ Enter the second string: “);
gets(str2);
/* See how long the strings are */
printf( “ %s is %d characters long \n “, str1, strlen(str1));
printf( “ %s is %d characters long \n “, str2, strlen(str2));
/* Compare the strings */
i = strcmp(str1, str2);
if ( ! i)
printf(“The strings are equal. \n”);
else if (i < 0)
printf(“%s is less than %s \n“, str1,str2);
else
printf(“%s is greater than %s \n“, str1,str2);
/* Concatenate str2 to end of str1 if there is enough room */
if (strlen(str1) + strlen(str2) < 80)
{
strcat(str1, str2);
printf( “%s \n”, str1);
}
/* copy str2 to str1 */
strcpy(str1, str2);
printf( “%s %s \n”, str1, str2);
return 0;
}
Note:
You can use scanf( ) to read a string using the %s specifier, but you probably won’t need to.
Why? This is because when scanf( ) inputs a string, it stops reading that string when the first
white space character is encountered. A white space character is a space, a tab, or a new line.
This means that you cannot use scanf() to read input like the following string.
Because there is a space after the word This, scanf( ) will stop inputting the string at that point. That is
why gets( ) is generally used to input strings.
Revision Exercises