~ Introduction to Programming: C ~

Session 12 - Arrays and Strings

<<  Back to Contents Page

Session 12 - Arrays and Strings 

In This Session...

In this session we will be covering the following topics:-

Review of Last Session

Last session we covered:-

The Array

In this session we will look at the idea of an array. This is a way of getting multiple pieces of information into one variable. We will also look at a specific type of array - the character array, also known as a character string - and how to use it for forming, inputting, outputting and storing words and sentences.

Up to now, we have looked at variables as named storage areas (like labelled boxes) that store a single piece of information.

For example:-

int day, month, year;

would define three different variables, each of which can store a single whole number - e.g. my birthday is 5th June 1972, so we might store this in our variables as follows:-

day = 5;  month = 6;  year = 1972;

Similarly, if we wanted to store five different numbers and then total them, we would have to declare five variables (plus perhaps one for the total). E.g.

#include <stdio.h>
#include <conio.h>
 
main()
{
  int num1, num2, num3, num4, num5, total;
  scanf ( "%d", &num1 );
  scanf ( "%d", &num2 );
  scanf ( "%d", &num3 );
  scanf ( "%d", &num4 );
  scanf ( "%d", &num5 );
  total = num1 + num2 + num3 + num4 + num5;
  printf ( "Total is %3d\n", total );
  getch();
}

With five numbers this is fairly easy. But what if we were storing a hundred items? What if the data was being read from a file from a supplier giving details of up to 20,000 orders at a time? Our programs would become rather large and repetitive.

For this reason, most programming languages (including C) include the concept of an array. This is where our variable is allowed to store more than one item. All of the items in a single array variable must be the same type - e.g. an integer or a float or a char. This is not typically a problem, as you will undoubtedly be storing the same type of information repetitively, otherwise you would be using a different variable!

Exercise 43 - Array of integers

The above example would like this to store any number of items. Type it out and try it.

#include <stdio.h>
#include <conio.h>
#define NUM_ITEMS 5
 
main()
{
  int num[NUM_ITEMS], i, total;
 
  for ( i=0; i<NUM_ITEMS; i++ )
    scanf( "%d", &num[i] );
 
  total = 0;
  for ( i=0; i<NUM_ITEMS; i++ )
    total += num[i];
 
  printf ( "Total is %3d\n", total );
  getch();
}

Here, we have defined a constant value called NUM_ITEMS - this could be 5, or it could be 20000. The program will not be more complicated if we need to read in more items - we just change the value of NUM_ITEMS.

In this case, we have created a single variable to hold the list of numbers called num. Notice this time that we have the value of NUM_ITEMS in square brackets - i.e. this is really int num[5]; in the example above.  This value gives us the number of items that can be stored in the array variable. So that we know which item to store an individual number into, we number them from zero upwards. So, if we declare the num variable to have five items, as in this case, then the five items will be referred to as num[0] for the first item, num[1] for the second, num[2] for the third, num[3] for the fourth, and num[4] for the fifth. Therefore, the numbers you use to access the individual data items inside the array variable run from zero (0) to the number of items you have defined minus 1 - e.g. declaring int num[5] gives you items num[0] to num[4]. If you try to access num[5] then this does not exist, and you could be accessing another variable (or some other part of your computer's memory) in error. It is an easy mistake to make, even by experienced programmers, so always watch out for this one.

 

The above example shows an array of five integers, which hold 5, 8, 2, 9 and 1 for items number 0, 1, 2, 3, and 4 respectively.

For example, to set the variables:-

int num[5];
num[0] = 5; num[1] = 8; num[2] = 2; num[3] = 9; num[4] = 1;

... and to display them on the screen:-

printf( "Numbers: %d,%d,%d,%d,%d\n", num[0], num[1], num[2], num[3], num[4] );

... and to display them on the screen:-

printf( "Numbers: %d,%d,%d,%d,%d\n", num[0], num[1], num[2], num[3], num[4] );

Exercise 44 - Putting values into an array 

Take a look at the following commands:-

int num[5];
num[0]=5; num[1]=2; num[2]=num[0]; num[3]=num[2]+num[1]; num[4]=3 * num[3];

What would you expect the values of num[0] through to num[4] to be?

Looking back at our example, we can see that we can obtain input from the keyboard using scanf as normal on each of the array items or elements, running from 0 to NUM_ITEMS (i.e. 5 at this point) minus 1. Thus, a loop is used to count through each of the element index numbers from 0 to 4. Thus, i starts at the first element number (0), and the condition around the loop is that i must be less than the value of NUM_ITEMS (i.e. less than 5 - so anything up to and including 4). Then, each time around the for loop, the index counter variable i is increased by 1. In this way, we can loop around and get as many items as is required by the value of the NUM_ITEMS constant - whether it be 5 or 5000.

  total = 0;
  for ( i=0; i<NUM_ITEMS; i++ )
    total += num[i];

This part of the program totals the values inside the various elements of the specific array variable. In this case, the total starts off as 0, and then a count is made from 0 to NUM_ITEMS-1 (i.e. 4).

The value inside each of these index-numbered variable elements is then added to the current value of the total variable. This effectively adds together all of the items inside the num array, however many items there are.

Character Arrays

We have looked at variables that hold single characters - typically to store a single key that is pressed on the keyboard - e.g. 

char ch;
ch = getch();
printf( "You pressed %c\n", ch );

If you look at a word or sentence - e.g. "Hello World" - it is really a number of single characters stringed together to form a sentence. In a sense, it is an array of characters.

We can store sentences in C using an array of characters. In order to show where the end of a sentence in in the array, we ensure that the last character in the sentence is a character with ASCII value 0 - this is known as the NULL character.

Exercise 45 - Building a character array

Type in (or copy) the following program and execute it:-

#include <stdio.h>
#include <conio.h>
#define NUM_ITEMS 5
 
main()
{
  char str[12];
 
  str[0]='H'; str[1]='e'; str[2]='l'; str[3]='l'; str[4]='o';
  str[5]=' '; str[6]='W'; str[7]='o'; str[8]='r'; str[9]='l';
  str[10]='d'; str[11]='\0';
 
  printf( "Your string is: %s", str ); getch();
}

Note the use of the '\0' character - this is an 'escaped character' which means that the backslash changes the meaning of the following character - in this case to mean a null value (i.e. ASCII character value 0) - e.g. \n would be new-line which is translated to ASCII value 10 etc.

This is building up the string by setting each character in the array, so that the entire array looks something like the table below at the end,  

str[number]
0
1
2
3
4
5
6
7
8
9
10
11
Contents
H
e
l
l
o
 
W
o
r
l
d
\0
ASCII code
72
101
108
108
111
32
87
111
114
108
100
0

To do this for every sentence that we wish to use would be unmanageably laborious.

The string.h library

For this reason, we make use of a library of functions that deals with strings called string by including the line:-

#include <string.h>

at the top of any programs we wish to write that will use strings of characters (just called strings for short).

A string is represented in a C program by enclosing it with double-quotes. So when we have been using a function such as printf as follows:-

printf("Hello World");

we have actually asked the C compiler to create an array that can hold 12 characters containing the given twelve characters (plus a zero character added automatically by the compiler to all string constants), and passed that array into the printf function for it to show the contents of the array on the screen.

For some reason known only to the creators of the C language, we cannot do something like this in C:-

char str[12];
str="Hello World";

Instead, we need to utilise a function within the string.h library called strcpy (short for string copy). So the above could be accomplished as follows:-

char str[12];
strcpy( str, "Hello World" );
printf( "String is %s", str );

So two pieces of information (parameters) are passed to the strcpy function - the first is the destination array where the information is to be copied into (str), the second the source array where the information is to be copied from ("Hello World" constant).

What is happening, is that the locations of the str array and the array created for the "Hello World" constant are passed into the strcpy function, and the letters are copied from "Hello World" to str a character at a time. The strcpy function only stops copying when it reaches a NULL character - i.e. ASCII character zero.

If it doesn't reach this zero ('\0') character, then it will try to access memory beyond the end of the array, and you could be reading from / writing to memory that is used for anything - e.g. other data used by your program. Typically, trying to do this will generate an unpredictable error and cause your program (or possibly computer!) to stop working. Careful with this one.

The final line shows an example of using the %s modifier inside a printf function to show where a string (or character array) variable is to be placed. As usual, the name of the array to go into that place follows after a comma.

A final note of warning: When you decide how long your array needs to be to fit a sentence into it, leave plenty of room, and remember to leave an extra character for the terminating zero / NULL character - e.g. "Hello World" is only eleven characters long, but add the terminating null, and you need a character array of 12 to fit the string in properly.

Exercise 46 - Using strcpy

Change the program you typed out for exercise 45:-

Using printf with strings 

We have seen that to show a string variable within another string, we can use the printf function with the %s modifier - e.g.

char str[12];
...
printf( "String is %s", str );

It is also possible to set a length for a string to be displayed - rather like %5d means "show an integer and insert spaces to the left if it is less than five digits in length".

For a string, we would use %5s if we wanted to insert spaces to the left to ensure the string takes up at least five spaces. This can be useful when displaying lists of items which you would like to be lined up into columns.

Exercise 47 - Strange Sentences

Try the following program, which puts together sentences using phrases which would make sense if they corresponded, but introduce an element of randomness, and the sentences can get quite interesting!

#include <stdio.h>

#include <conio.h>

#include <string.h>

#include <stdlib.h>

#include <time.h>



main()

{

  char subject[50], verb[50], noun[50];

  int i;



  srand( (unsigned int) time( NULL ) );



  i = rand () % 3;

  switch ( i ) {

    case(0) : strcpy( subject, "The drunken man" );

              break;

    case(1) : strcpy( subject, "The cackling witch" );

              break;

    case(2) : strcpy( subject, "The agile acrobat" );

  }



  i = rand () % 3;

  switch ( i ) {

    case(0) : strcpy( verb, "ate painfully" );

              break;

    case(1) : strcpy( verb, "boiled steadily" );

              break;

    case(2) : strcpy( verb, "easily juggled" );

  }



  i = rand () % 3;

  switch ( i ) {

    case(0) : strcpy( noun, "a blazing vindaloo" );

              break;

    case(1) : strcpy( noun, "several newt eyes" );

              break;

    case(2) : strcpy( noun, "two large balls" );

  }



  printf( "%s %s %s", subject, verb, noun );
  getch();

}

Notice that the size of the arrays are much larger than the sizes that could be used. This is OK, so long as the arrays are not too SMALL - it just means that some of the space will be wasted.  However, if we were to add some more items later, we might add larger strings, but forget to check the maximum sizes of the arrays. Providing a bit of lee-way decreases the chance of this happening, and introduces a 'safety margin'. 

Using scanf / gets with strings 

Similarly, to obtain a string from the keyboard, we using the %s modifier with the scanf function as follows:-

char str[100];
printf( "Enter a string: " );
scanf( "%s", &str );
printf( "You typed: %s\n, str );

Exercise 48 -  Customizing the strange sentences

Change the program you typed in exercise 47, so that each of the random items can pick an extra item which prompts the user for an input and places that input into the appropriate string variable (i.e. subject, verb or noun) so that the string the user inputs appears in the final sentence:- 

This identifies a problem with the scanf function. It will only read up to the first space, so anything with multiple words will not be scanned correctly, and only the first word will be read. Worse than this, any subsequent scanf statements will pick up the rest of what was input in the first scanf statement.

For this reason, it is better (and easier) with strings to use the gets function (means get string) as follows:-

gets(str);

Typical results might look something like this:-

Enter a subject: The angry aardvark

The angry aardvark ate painfully two large balls

or:-

Enter a verb: snorted painfully

The agile acrobat snorted painfully a blazing vindaloo

Solution to Exercise 44

The values of the variables is as follows after each successive statement being executed:-

Command to execute num[0] num[1] num[2] num[3] num[4]
num[0]=5; 5        
num[1]=2; 5 2      
num[2]=num[0]; 5 2 5    
num[3]=num[2]+num[1]; 5 2 5 5+2 = 7  
num[4]=3*num[3] 5 2 5 7 3*7 = 21

The last line shows the final values of each of the items (or elements) within the num array.

Solution to Exercise 46

The following is a solution exercise 46:-

#include <stdio.h>

#include <conio.h>

#include <string.h>



main()

{

  char ch[12];

  strcpy( ch, "Hello World" );

  printf( "Your string is: %s", ch );
  getch();

}

Solution to Exercise 48

The following is a solution exercise 48:-

#include <stdio.h>

#include <conio.h>

#include <string.h>

#include <stdlib.h>

#include <time.h>



main()

{

  char subject[20], verb[20], noun[20];

  int i;



  srand( (unsigned int) time( NULL ) );



  i = rand () % 4;

  switch ( i ) {

    case(0) : strcpy( subject, "The drunken man" );

              break;

    case(1) : strcpy( subject, "The cackling witch" );

              break;

    case(2) : strcpy( subject, "The agile acrobat" );

              break;

    case(3) : printf( "Enter a subject: " );

              gets( subject );

  }



  i = rand () % 4;

  switch ( i ) {

    case(0) : strcpy( verb, "ate painfully" );

              break;

    case(1) : strcpy( verb, "boiled steadily" );

              break;

    case(2) : strcpy( verb, "easily juggled" );

              break;

    case(3) : printf( "Enter a verb: " );

              gets( verb );

  }



  i = rand () % 4;

  switch ( i ) {

    case(0) : strcpy( noun, "a blazing vindaloo" );

              break;

    case(1) : strcpy( noun, "several newt eyes" );

              break;

    case(2) : strcpy( noun, "two large balls" );

              break;

    case(3) : printf( "Enter a noun: " );

              gets( noun );

  }



  printf( "%s %s %s", subject, verb, noun ); getch();

}

In the Next Session...

In the next session we will be covering the following topics:-

(c) Copyright 2002-4 Simon Huggins.   All Rights Reserved.
If you have any issues or questions regarding the content of this web site, please contact the author by clicking here.
Alternatively, you can leave a voice message on 00 44 (0)7050-618-297 or fax on 00 44 (0)7050-618-298

This Page was last updated: 29 January 2004 13:06