Objectives
Having read this section you should have a good understanding of the use of arrays in C.
Advanced Data Types
Programming in any language takes a quite significant leap forwards as soon as you learn about more advanced data types - arrays and strings of characters. In C there is also a third more general and even more powerful advanced data type - the pointer but more about that later. In this section we introduce the array, but the first question is, why bother?
There are times when we need to store a complete list of numbers or other data items. You could do this by creating as many individual variables as would be needed for the job, but this is a hard and tedious process. For example, suppose you want to read in five numbers and print them out in reverse order. You could do it the hard way as:
main()
{
int al,a2,a3,a4,a5;
scanf("%d %d %d %d %d",&a1,&a2,&a3,&a4,&a5);
printf("%d %d %d %d %d'',a5,a4,a3,a2,a1);
}
Doesn't look very pretty does it, and what if the problem was to read in 100 or more values and print them in reverse order? Of course the clue to the solution is the use of the regular variable names a1, a2 and so on. What we would really like to do is to use a name like a[i] where i is a variable which specifies which particular value we are working with. This is the basic idea of an array and nearly all programming languages provide this sort of facility - only the details alter.
In the case of C you have to declare an array before you use it - in the same way you have to declare any sort of variable. For example,
int a[5];
declares an array called a with five elements. Just to confuse matters a little the first element is a[0] and the last a[4]. C programmer's always start counting at zero! Languages vary according to where they start numbering arrays. Less technical, i.e. simpler, languages start counting from 1 and more technical ones usually start counting from 0. Anyway, in the case of C you have to remember that
type array[size]
declares an array of the specified type and with size elements. The first array element is array[0] and the last is array[size-1].
Using an array, the problem of reading in and printing out a set of values in reverse order becomes simple:
main()
{
int a[5];
int i;
for(i =0;i < 5; ++i) scanf("%d",&a[i]);
for(i =4;i> =0;--i) printf("%d",a[i]);
}
Thursday, November 13, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment