Lecture6 Complex C Data Types
Lecture6 Complex C Data Types
1
Arrays
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:
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);
What if the problem was read 100 or more values and print it in reverse order?
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.
In C, the fundamental data type is the array, and strings are grafted on. For
example, if you try something like:
char name[40]; name="Hello" it will not work.
How to initialize strings? You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd"; c[0] c[1] c[2] c[3] c[4]
char c[] = {'a', 'b', 'c', 'd', '\0'}; a b c d \0
char c[5] = {'a', 'b', 'c', 'd', '\0'};
However, you can print strings using printf and read them into character
arrays using scanf.
void main(void)
{
char name[40] ="hello";
printf("%s\n",name);
scanf("%s",name);
printf("%s",name);
}
This program reads in the text that you type, terminating it with a null and
stores it in the character array name.
It then prints the character array treating it as a string, i.e. stopping when it
hits the first null string.
Note the use of the "%s" format descriptor in scanf and printf to specify that
what is being printed is a string.