If you need help just do post.
I will help you.
thank you
Strings
Objectives
This section brings together the use of two of C's fundamental data types, ponters and arrays, in the use of handling strings.
Having read this section you should be able to:
1. handle any string constant by storing it in an array.
Stringing Along
Now that we have mastered pointers and the relationship between arrays and pointers we can take a second look at strings. A string is just a character array with the convention that the end of the valid data is marked by a null '\0'. Now you should be able to see why you can read in a character string using scanf("%s", name) rather than scanf("%s",&name) - name is already a pointer variable. Manipulating strings is very much a matter of pointers and special string functions. For example, the strlen(str) function returns the number of characters in the string str. It does this simply by counting the number of characters up to the first null in the character array - so it is important that you are using a valid null-terminated string. Indeed this is important with all of the C string functions.
You might not think that you need a function to copy strings, but simple assignment between string variables doesn't work. For example:
char a[l0],b[10];
b = a;
does not appear to make a copy of the characters in a, but this is an illusion. What actually happens is that the pointer b is set to point to the same set of characters that a points to, i.e. a second copy of the string isn't created.
To do this you need strcopy(a,b) which really does make a copy of every character in a in the array b up to the first null character. In a similar fashion strcat(a,b) adds the characters in b to the end of the string stored in a. Finally there is the all-important strcmp(a,b) which compares the two strings character by character and returns true - that is 0 - if the results are equal.
Again notice that you can't compare strings using a==b because this just tests to see if the two pointers a and b are pointing to the same memory location. Of course if they are then the two strings are the same, but it is still possible for two strings to be the same even if they are stored at different locations.
You can see that you need to understand pointers to avoid making simple mistakes using strings. One last problem is how to initialise a character array to a string. You can't use:
a = "hello";
because a is a pointer and "hello" is a string constant. However, you can use:
strcopy(a,"hello")
because a string constant is passed in exactly the same way as a string variable, i.e. as a pointer. If you are worried where the string constant is stored, the answer is in a special area of memory along with all of the constants that the program uses. The main disadvantage of this method is that many compilers use an optimisation trick that results in only a single version of identical constants being stored. For example:
strcopy(b,"hello");
usually ends up with b pointing to the same string as a. In other words, this method isn't particularly safe!
A much better method is to use array initialisation. You can specify constants to be used to initialise any variable when it is declared. For example:
int a=10;
declares a to be an integer and initialises it to 10. You can initialise an array using a similar notation. For example:
int a[5] = {1,2,3,4,5};
declares an integer array and initialises it so that a[0]= 1, a[1] = 2 and so on. A character array can be initialised in the same way. For example:
char a[5]={'h','e','l','l','o'};
but a much better way is to write:
char a[6]="hello";
which also automatically stores a null character at the end of the string - hence a[6] and not a[5]. If you really want to be lazy you can use:
char a[] = "hello";
and let the compiler work out how many array elements are needed. Some compilers cannot cope with the idea of initialising a variable that doesn't exist for the entire life of the program. For those compilers to make initialisation work you need to add the keyword static to the front of the string declaration, therefore:
static char a[] = "hello";
As easy as... B or C?
A few words of warning. If you are familiar with BASIC then you will have to treat C strings, and even C arrays, with some caution. They are not as easy or as obvious to use and writing a program that manipulates text is harder in C than in BASIC. If you try to use C strings as if it were BASIC strings you are sure to create some very weird and wonderful bugs!
A Sort Of Bubble Program
This sections program implements a simple bubble sort - which is notorious for being one of the worst sorting methods known to programmer-kind, but it does have the advantage of being easy and instructive. Some of the routines have already been described in the main text and a range of different methods of passing data in functions have also been used.
The main routine is sort which repeats the scan function on the array until the variable done is set to 0. The scan function simply scans down the array comparing elements that are next door to each other. If they are in the wrong order then function swap is called to swap them over.
Study this program carefully with particular attention to the way arrays, array elements and variables are passed. It is worth saying that in some cases there are better ways of achieving the same results. In particular, it would have been easier not to use the variable done, but to have returned the state as the result of the scan function.
#include
void randdat(int a[] , int n);
void sort(int a[] , int n);
void scan(int a[] , int n , int *done);
void swap(int *a ,int *b);
main()
{
int i;
int a[20];
randdat(a , 20);
sort(a , 20);
for(i=0;i<20;++i) printf("%d\n" ,a[i]);
}
void randdat(int a[1] , int n)
{
int i;
for (i=0 ; i
}
void sort(int a[1] , int n)
{
int done;
done = 1;
while(done == 1) scan(a , n , &done);
}
void scan(int a[1] , int n , int *done)
{
int i;
*done=0;
for(i=0 ; i
if(a[i] {
swap(&a[i],&a[i+1]);
*done=1;
}
}
}
void swap(int *a ,int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
[program]
Pointers
Objectives
Having read this section you should be able to:
- program using pointers
- understand how C uses pointers with arrays
Point to Point
Pointers are a very powerful, but primitive facility contained in the C language. Pointers are a throwback to the days of low-level assembly language programming and as a result they are sometimes difficult to understand and subject to subtle and difficult-to-find errors. Still it has to be admitted that pointers are one of the great attractions of the C language and there will be many an experienced C programmer spluttering and fuming at the idea that we would dare to refer to pointers as 'primitive'!In an ideal world we would avoid telling you about pointers until the very last minute, but without them many of the simpler aspects of C just don't make any sense at all. So, with apologies, let's get on with pointers.
A variable is an area of memory that has been given a name. For example:
int x;
is an area of memory that has been given the name x. The advantage of this scheme is that you can use the name to specify where to store data. For example:
x=lO;
is an instruction to store the data value 10 in the area of memory named x. The variable is such a fundamental idea that using it quickly becomes second nature, but there is another way of working with memory.
The computer access its own memory not by using variable names but by using a memory map with each location of memory uniquely defined by a number, called the address of that memory location.
A pointer is a variable that stores this location of memory. In more fundamental terms, a pointer stores the address of a variable . In more picturesque terms, a pointer points to a variable.
A pointer has to be declared just like any other variable - remember a pointer is just a variable that stores an address. For example,
int *p;
is a pointer to an integer. Adding an asterisk in front of a variable's name declares it to be a pointer to the declared type. Notice that the asterisk applies only to the single variable name that it is in front of, so:
int *p , q;
declares a pointer to an int and an int variable, not two pointers.
Once you have declared a pointer variable you can begin using it like any other variable, but in practice you also need to know the meaning of two new operators: & and *. The & operator returns the address of a variable. You can remember this easily because & is the 'A'mpersand character and it gets you the 'A'ddress. For example:
int *p , q;
declares p, a pointer to int, and q an int and the instruction:
p=&q;
stores the address of q in p. After this instruction you can think of p as pointing at q. Compare this to:
p=q;
which attempts to store the value in q in the pointer p - something which has to be considered an error.
The second operator * is a little more difficult to understand. If you place * in front of a pointer variable then the result is the value stored in the variable pointed at. That is, p stores the address, or pointer, to another variable and *p is the value stored in the variable that p points at.
The * operator is called the de-referencing operator and it helps not to confuse it with multiplication or with its use in declaring a pointer.
This multiple use of an operator is called operator overload.
Confused? Well most C programmers are confused when they first meet pointers. There seems to be just too much to take in on first acquaintance. However there are only three basic ideas:
- To declare a pointer add an * in front of its name.
- To obtain the address of a variable us & in front of its name.
- To obtain the value of a variable use * in front of a pointer's name.
Now see if you can work out what the following means:
int *a , b , c;
b = 10;
a = &b;
c = *a;
Firstly three variables are declared - a (a pointer to int), and b and c (both standard integers). The instruction stores the value l0 in the variable b in the usual way. The first 'difficult' instruction is a=&b which stores the address of b in a. After this a points to b.
Finally c = *a stores the value in the varable pointed to by a in c. As a points to b, its value i.e. 1O is stored in c. In other words, this is a long winded way of writing
c = b;
Notice that if a is an int and p is a pointer to an int then
a = p;
is nonsense because it tries to store the address of an int, i.e. a pointer value, in an int. Similarly:
a = &p;
tries to store the address of a pointer variable in a and is equally wrong! The only assignment between an int and a pointer to int that makes sense is:
a = *p;
Swap Shop
At the moment it looks as if pointers are just a complicated way of doing something we can already do by a simpler method. However, consider the following simple problem - write a function which swaps the contents of two variables. That is, write swap(a,b) which will swaps over the contents of a and b. In principle this should be easy:
function swap(int a , int b);
{
int temp;
temp = a;
a = b;
b = temp;
}
the only complication being the need to use a third variable temp to hold the value of a while the value of b overwrites it. However, if you try this function you will find that it doesn't work. You can use it - swap(a,b); - until you are blue in the face, but it just will not change the values stored in a and b back in the calling program. The reason is that all parameters in C are passed by value. That is, when you use swap(a,b) function the values in a and b are passed into the function swap via the parameters and any changes that are made to the parameters do not alter a and b back in the main program. The function swap does swap over the values in a and b within the function, but doesn't do so in the main program.
The solution to this very common problem is to pass not the values stored in the variables, but the addresses of the variables. The function can then use pointers to get at the values in the variables in the main program and modify them. That is, the function should be:
function swap(int *a , int *b);
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Notice that now the two parameters a and b are pointers and the assignments that effect the swap have to use the de-reference operator to make sure that it is the values of the variables pointed at that are swapped. You should have no difficulty with:
temp = *a;
this just stores the value pointed at by a into temp. However,
*a = *b;
is a little more unusual in that it stores that value pointed at by b in place of the value pointed at by a. There is one final complication. When you use swap you have to remember to pass the addresses of the variables that you want to swap. That is not:
swap(a,b)
but
swap(&a,&b)
The rule is that whenever you want to pass a variable so that the function can modify its contents you have to pass it as an address. Equally the function has to be ready to accept an address and work with it. You can't take any old function and suddenly decide to pass it the address of a variable instead of its value. If you pass an address to a function that isn't expecting it the result is usually disaster and the same is true if you fail to pass an address to a function that is expecting one.
For example, calling swap as swap(a,b) instead of swap(&a,&b) will result in two arbitrary areas of memory being swapped over, usually with the result that the entire system, not just your program, crashes.
The need to pass an address to a function also explains the difference between the two I/O functions that we have been using since the beginning of this course. printf doesn't change the values of its parameters so it is called as printf("%d",a) but scanf does, because it is an input function, and so it is called as scanf("%d",&a).
Pointers And Arrays
In C there is a very close connection between pointers and arrays. In fact they are more or less one and the same thing! When you declare an array as:int a[10];
you are in fact declaring a pointer a to the first element in the array. That is, a is exactly the same as &a[0]. The only difference between a and a pointer variable is that the array name is a constant pointer - you cannot change the location it points at. When you write an expression such as a[i] this is converted into a pointer expression that gives the value of the appropriate element. To be more precise, a[i] is exactly equivalent to *(a+i) i.e. the value pointed at by a + i . In the same way *(a+ 1) is the same as a[1] and so on.
Being able to add one to a pointer to get the next element of an array is a nice idea, but it does raise the question of what it means to add 'one' to a pointer. For example, in most implementations an int takes two memory locations and a float takes four. So if you declare an int array and add one to a pointer to it, then in fact the pointer will move on by two memory locations. However, if you declare a float array and add one to a pointer to it then the pointer has to move on by four memory locations. In other words, adding one to a pointer moves it on by an amount of storage depending on the type it is a pointer to.
This is, of course, precisely why you have to declare the type that the pointer is to point at! Only by knowing that a is a pointer to int and b is a pointer to float can the compiler figure out that
a + 1
means move the pointer on by two memory locations i.e. add 2, and
b + 1
means move the pointer on by four memory locations i.e. add 4. In practice you don't have to worry about how much storage a pointer's base type takes up. All you do need to remember is that pointer arithmetic works in units of the data type that the pointer points at. Notice that you can even use ++ and -- with a pointer, but not with an array name because this is a constant pointer and cannot be changed. So to summarise:
- An array's name is a constant pointer to the first element in the array that is a==&a[0] and *a==a[0].
- Array indexing is equivalent to pointer arithmetic - that is a+i=&a[i] and *(a+i)==a[i].
One final point connected with both arrays and functions is that when you pass an entire array to a function then by default you pass a pointer. This allows you to write functions that process entire arrays without having to pass every single value stored in the array - just a pointer to the first element. However, it also temps you to write some very strange code unless you keep a clear head. Try the following - write a function that will fill an array with random values randdat(a,n) where a is the array and n is its size. Your first attempt might be something like:
void randdat(int *pa , int n)
{
for (pa = 0 ; pa < n ; pa++ ) *pa = rand()%n + 1;
}
Well I hope your first attempt wouldn't be like this because it is wrong on a number of counts! The problem is that the idea of a pointer and the idea of an index have been confused. The pointer pa is supposed to point to the first element of the array, but the for loop sets it to zero and then increments it though a series of memory locations nowhere near the array. A lesser error is to suppose that n-1 is the correct final value of the array pointer! As before, you will be lucky if this program doesn't crash the system, let alone itself! The correct way of doing the job is to use a for loop to step from 0 to n-1, but to use pointer arithmetic to access the correct array element:
int randdat(int *pa , int n)
{
int i;
for ( i=0 ; i< n ; ++i)
{
*pa = rand()%n + 1;
++pa;
}
}
Notice the way that the for loop looks just like the standard way of stepping through an array. If you want to make it look even more like indexing an array using a for loop you could write:
for(i=0 ; i
or even:
for(i=0 ; i
In other words, as long as you define pa as a pointer you can use array indexing notation with it and it looks as if you have actually passed an array. You can even declare a pointer variable using the notation:
int pa[];
that is, as an array with no size information. In this way the illusion of passing an array to a function is completeArrays
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]);
}
[program]
Well we said simple but I have to admit that the pair of for loops looks a bit intimidating. The for loop and the array data type were more or less made for each other. The for loop can be used to generate a sequence of values to pick out and process each element in an array in turn. Once you start using arrays, for loops like:
for (i=0 ; i<5>
to generate values in the order 0,1,2 and so forth, and
for(i=4;i>=0;--i)
to generate values in the order 4,3,2... become very familiar.
In Dis-array
An array of character variables is in no way different from an array of numeric variables, but programmers often like to think about them in a different way. For example, if you want to read in and reverse five characters you could use:
main()
{
char a[5];
int i;
for(i=0; i<5; ++i) scanf("%c",&a[i]);
for(i=4;i>=0;--i) printf("%c",a[i]);
}
Notice that the only difference, is the declared type of the array and the %c used to specify that the data is to be interpreted as a character in scanf and printf. The trouble with character arrays is that to use them as if they were text strings you have to remember how many characters they hold. In other words, if you declare a character array 40 elements long and store H E L L O in it you need to remember that after element 4 the array is empty. This is such a nuisance that C uses the simple convention that the end of a string of characters is marked by a null character. A null character is, as you might expect, the character with ASCII code 0. If you want to store the null character in a character variable you can use the notation \0 - but most of the time you don't have to actually use the null character. The reason is that C will automatically add a null character and store each character in a separate element when you use a string constant. A string constant is indicated by double quotes as opposed to a character constant which is indicated by a single quote. For example:
"A"
is a string constant, but
'A'
is a character constant. The difference between these two superficially similar types of text is confusing at first and the source of many errors. All you have to remember is that "A" consists of two characters, the letter A followed by \0 whereas 'A' is just the single character A. If you are familiar with other languages you might think that you could assign string constants to character arrays and work as if a string was a built-in data type. In C however the fundamental data type is the array and strings are very much grafted on. For example, if you try something like:
char name[40];
name="Hello"
it will not work. However, you can print strings using printf and read them into character arrays using scanf. For example,
main()
{
static char name[40] ="hello";
printf("%s",name);
scanf("%s",name);
printf("%s",name);
}
[program]
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. Notice the use of the "%s" format descriptor in scanf and printf to specify that what is being printed is a string.
At this point the way that strings work and how they can be made a bit more useful and natural depends on understanding pointers which is covered in the next section.
Data Types Part II
Objectives
So far we have looked at local variable now we switch our attention to other types of variables supported by the C programming language:
- Global Variables
- Constant Data Types
Global variables
Variables can be declared as either local variables which can be used inside the function it has been declared in (more on this in further sections) and global variables which are known throughout the entire program. Global variables are created by declaring them outside any function. For example:
The int max can be used in both main and function f1 and any changes made to it will remain consistent for both functions. The understanding of this will become clearer when you have studied the section on functions but I felt I couldn't complete a section on data types without mentioning global and local variables.
int max;
main()
{
.....
}
f1()
{
.....
}
Constant Data Types
Constants refer to fixed values that may not be altered by the program. All the data types we have previously covered can be defined as constant data types if we so wish to do so. The constant data types must be defined before the main function. The format is as follows:#define CONSTANTNAME value
for example:
#define SALESTAX 0.05
The constant name is normally written in capitals and does not have a semi-colon at the end. The use of constants is mainly for making your programs easier to be understood and modified by others and yourself in the future. An example program now follows:
#define SALESTAX 0.05
#include
main()
{
float amount, taxes, total;
printf("Enter the amount purchased : ");
scanf("%f",&amount);
taxes = SALESTAX*amount;
printf("The sales tax is £%4.2f",taxes);
printf("\n The total bill is £%5.2f",total);
}
The float constant SALESTAX is defined with value 0.05. Three float variables are declared amount, taxes and total. Display message to the screen is achieved using printf and user input handled by scanf. Calculation is then performed and results sent to the screen. If the value of SALESTAX alters in the future it is very easy to change the value where it is defined rather than go through the whole program changing the individual values separately, which would be very time consuming in a large program with several references. The program is also improved when using constants rather than values as it improves the clarity.
Functions and Prototypes
Objectives
Having read this section you should be able to:
- program using correctly defined C functions
- pass the value of local variables into your C functions
Functions - C's Building Blocks
Some programmers might consider it a bit early to introduce the C function - but we think you can't get to it soon enough. It isn't a difficult idea and it is incredibly useful. You could say that you only really start to find out what C programming is all about when you start using functions.C functions are the equivalent of what in other languages would be called subroutines or procedures. If you are familiar with another language you also need to know that C only has functions, so don't spend time looking for the definition of subroutines or procedures - in C the function does everything!
A function is simply a chunk of C code (statements) that you have grouped together and given a name. The value of doing this is that you can use that "chunk" of code repeatedly simply by writing its name. For example, if you want to create a function that prints the word "Hello" on the screen and adds one to variable called total then the chunk of C code that you want to turn into a function is just:
printf("Hello");
total = total + l;
To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single compound statement and write the name that you want to give it in front of the brackets:
demo()
{
printf("Hello");
total = total + 1;
}
Don't worry for now about the curved brackets after the function's name. Once you have defined your function you can use it within a program:
In this program the instruction demo (); is entirely equivalent to writing out all of the statements in the function. What we have done is to create an new C function and this, of course, is the power of functions. When you are first introduced to the idea of functions, or their equivalent in other languages, it is easy to fall into the trap of thinking that they are only useful when you want to use a block of code more than once.
main()
{
demo();
}
Functions are useful here but they have a more important purpose. If you are creating a long program then functions allow you to split it into "bite-sized" chunks which you can work on in isolation. As every C programmer knows, "functions are the building blocks of programs."
Functions and Local Variables
Now that the philosophy session is over we have to return to the details - because as it stands the demo function will not work. The problem is that the variable total isn't declared anywhere. A function is a complete program sub-unit in its own right and you can declare variables within it just as you can within the main program. If you look at the main program we have been using you will notice it is in fact a function that just happens to be called "main"! So to make demo work we have to add the declaration of the variable total:
demo()
{
int total;
printf("Hello");
total=total+1;
}
Now this raises the question of where exactly total is a valid variable. You can certainly use total within the function that declares it - this much seems reasonable - but what about other functions and, in particular, what about the main program? The simple answer is that total is a variable that belongs to the demo function. It cannot be used in other functions, it doesn't even exist in other functions and it certainly has nothing to do with any variable of the same name that you declare within other functions.
This is what we hinted at when we said that functions were isolated chunks of code. Their isolation is such that variables declared within the function can only be used within that function. These variables are known as local variables and as their name suggests are local to the function they have been declared in. If you are used to a language where every variable is usable all the time this might seem silly and restrictive - but it isn't. It's what makes it possible to break a large program down into smaller and more manageable chunks.
The fact that total is only usable within the demo function is one thing - but notice we said that it only existed within this function, which is a more subtle point. The variables that a function declares are created when the function is started and destroyed when the function is finished. So if the intention is to use total to count the number of times the >demo function is used - forget it! Each time demo is used the variable total is created afresh, and at the end of the function the variable goes up in a puff of smoke along with its value. So no matter how many times you run demo total will only ever reach a value of 1, assuming that it's initialised to 0.
Making The Connections
Functions are isolated, and whats more nothing survives after they have finished. Put like this a function doesn't seem to be that useful because you can't get data values in, you can't get data values out, and they don't remember anything that happens to them!To be useful there has to be a way of getting data into and out of a function, and this is the role of the curved brackets. You can define special variables called parameters which are used to carry data values into a function. Parameters are listed and declared in between the () brackets in the function's definition. For example:
defines a function called sum with two parameters a and b, both integers. Notice that the result variable is declared in the usual way within the body of the function. Also, notice that the parameters a and b are used within the function in the same way as normal variables - which indeed they are. What is more, they are still local variables and have nothing at all to do with any variables called a and b defined in any other function.
sum( int a, int b)
{
int result;
result=a + b;
}
The only way in which parameters are any different is that you can give them initial values when the function starts by writing the values between the round brackets. So
sum(l,2);
is a call to the sum function with a set to 1 and b set to 2 and so result is set to 3. You can also initialise parameters to the result of expressions such as:
sum(x+2,z*10);
which will set a equal to whatever x+2 works out to be and b equal to whatever z*10 works out to be.
As a simpler case you can also set a parameter to the value in a single variable - for example:
sum(x,y);
will set a to the value stored in x and b to the value stored in y.
Parameters are the main way of getting values into a function, but how do we get values out? There is no point in expecting the >result variable to somehow magically get its value out of the sum function - after all, it is a local variable and is destroyed when sum is finished. You might try something like:
sum(int a, int b, int result)
{
int result;
result = a + b;
}
but it doesn't work. Parameters are just ordinary variables that are set to an initial value when the function starts running - they don't pass values back to the program that used the function. That is:
sum(l,2,r);
doesn't store 1+2 in r because the value in r is used to initialise the value in result and not vice versa. You can even try
sum(l,2,result);
and it still will not work - the variable result within the function has nothing to do with the variable result used in any other program.
The simplest way to get a value out of a function is to use the return instruction. A function can return a value via its name - it's as if the name was a variable and had a value. The value that is returned is specified by the instruction:
return value;
which can occur anywhere within the function, not just as the last instruction - however, a return always terminates the function and returns control back to the calling function. The only complication is that as the function's name is used to return the value it has to be given a data type. This is achieved by writing the data type in front of the function's name. For example:
int sum(a,b);
So now we can at last write the correct version of the sum function:
int sum(int a, int b)
{
int result;
result = a + b;
return result;
}
and to use it you would write something like:
r=sum(1,2);
which would add 1 to 2 and store the result in r. You can use a function anywhere that you can use a variable. For example,
r=sum(1,2)*3
is perfectly OK, as is
r=3+sum(1,2)/n-10
Obviously, the situation with respect to the number of inputs and outputs of a function isn't equal. That is you can create as many parameters as you like but a function can return only a single value. (Later on we will have to find ways of allowing functions to return more than one value.)
So to summarise: a function has the general form:
and of course a function can contain any number of return statements to specify its return value and bring the function to an end.
type FunctionName(type declared parameter list)
{
statements that make up the function
}
There are some special cases and defaults we need to look at before moving on. You don't have to specify a parameter list if you don't want to use any parameters - but you still need the empty brackets! You don't have to assign the function a type in which case it defaults to int. A function doesn't have to return a value and the program that makes use of a function doesn't have to save any value it does return. For example, it is perfectly OK to use:
sum(1,2);
which simply throws away the result of adding 1 to 2. As this sort of thing offends some programmers you can use the data type void to indicate that a function doesn't return a value. For example:
void demo();
is a function with no parameters and no return value.
void is an ANSI C standard data type.
The break statement covered in a previous section can be used to exit a function. The break statement is usually linked with an if statement checking for a particular value. For example:
if (x==1) break;
If x contained 1 then the fuction would exit and return to the calling program.
Functions and Prototypes
Where should a function's definition go in relation to the entire program - before or after main()? The only requirement is that the function's type has to be known before it is actually used. One way is to place the function definition earlier in the program than it is used - for example, before main(). The only problem is that most C programmers would rather put the main program at the top of the program listing. The solution is to declare the function separately at the start of the program. For example:declares the name sum to be a function that returns an integer. As long as you declare functions before they are used you can put the actual definition anywhere you like.
int sum();
main()
{
etc...
By default if you don't declare a function before you use it then it is assumed to be an int function - which is usually, but not always, correct. It is worth getting into the habit of putting function declarations at the start of your programs because this makes them easier to convert to full ANSI C.
What is ANSI C?
When C was first written the standard was set by its authors Kernighan and Ritche - hence "K&R C". In 1990, an international ANSI standard for C was established which differs from K&R C in a number of ways.The only really important difference is the use of function prototypes. To allow the compiler to check that you are using functions correctly ANSI C allows you to include a function prototype which gives the type of the function and the type of each parameter before you define the function. For example, a prototype for the sum function would be:
int sum(int,int);
meaning sum is an int function which takes two int parameters. Obviously, if you are in the habit of declaring functions then this is a small modification. The only other major change is that you can declare parameter types along with the function as in:
rather than:
int sum(int a, int b);
{
int sum(a,b)
int a,b;
{
was used in the original K&R C. Again, you can see that this is just a small change. Notice that even if you are using an ANSI compiler you don't have to use prototypes and the K&R version of the code will work perfectly well.
The Standard Library Functions
Some of the "commands" in C are not really "commands" at all but are functions. For example, we have been using printf and scanf to do input and output, and we have used rand to generate random numbers - all three are functions.There are a great many standard functions that are included with C compilers and while these are not really part of the language, in the sense that you can re-write them if you really want to, most C programmers think of them as fixtures and fittings. Later in the course we will look into the mysteries of how C gains access to these standard functions and how we can extend the range of the standard library. But for now a list of the most common libraries and a brief description of the most useful functions they contain follows:
- stdio.h: I/O functions:
- getchar() returns the next character typed on the keyboard.
- putchar() outputs a single character to the screen.
- printf() as previously described
- scanf() as previously described
- string.h: String functions
- strcat() concatenates a copy of str2 to str1
- strcmp() compares two strings
- strcpy() copys contents of str2 to str1
- ctype.h: Character functions
- isdigit() returns non-0 if arg is digit 0 to 9
- isalpha() returns non-0 if arg is a letter of the alphabet
- isalnum() returns non-0 if arg is a letter or digit
- islower() returns non-0 if arg is lowercase letter
- isupper() returns non-0 if arg is uppercase letter
- math.h: Mathematics functions
- acos() returns arc cosine of arg
- asin() returns arc sine of arg
- atan() returns arc tangent of arg
- cos() returns cosine of arg
- exp() returns natural logarithim e
- fabs() returns absolute value of num
- sqrt() returns square root of num
- time.h: Time and Date functions
- time() returns current calender time of system
- difftime() returns difference in secs between two times
- clock() returns number of system clock cycles since program execution
- stdlib.h:Miscellaneous functions
- malloc() provides dynamic memory allocation, covered in future sections
- rand() as already described previously
- srand() used to set the starting point for rand()
Throwing The Dice
As an example of how to use functions, we conclude this section with a program that, while it isn't state of the art, does show that there are things you can already do with C. It also has to be said that some parts of the program can be written more neatly with just a little more C - but that's for later. All the program does is to generate a random number in the range 1 to 6 and displays a dice face with the appropriate pattern.The main program isn't difficult to write because we are going to adopt the traditional programmer's trick of assuming that any function needed already exists. This approach is called stepwise refinement, and although its value as a programming method isn't clear cut, it still isn't a bad way of organising things:
main()
{
int r;
char ans;
ans = getans();
while(ans== 'y')
{
r = randn(6);
blines(25);
if (r==1) showone();
if (r==2) showtwo();
if (r==3) showthree();
if (r==4) showfour();
if (r==5) showfive();
if (r==6) showsix();
blines(21);
ans = getans();
}
blines(2);
}
If you look at main() you might be a bit mystified at first. It is clear that the list of if statements pick out one of the functions showone, showtwo etc. and so these must do the actual printing of the dot patterns - but what is blines, what is getans and why are we using randn()? The last time we used a random number generator it was called rand()!
The simple answers are that blines(n) will print n blank lines, getans() asks the user a question and waits for the single letter answer, and randn(n) is a new random number generator function that produces a random integer in the range 1 to n - but to know this you would have written the main program. We decided what functions would make our task easier and named them. The next step is to write the code to fill in the details of each of the functions. There is nothing to stop me assuming that other functions that would make my job easier already exist. This is the main principle of stepwise refinement - never write any code if you can possibly invent another function! Let's start with randn().
This is obviously an int function and it can make use of the existing rand() function in the standard library
int randn(int n)
{
return rand()%n + 1;
}
The single line of the body of the function just returns the remainder of the random number after dividing by n - % is the remainder operator - plus 1. An alternative would be to use a temporary variable to store the result and then return this value. You can also use functions within the body of other functions.
Next getans()
char getans()
{
int ans;
printf("Throw y/n ?");
ans = -1;
while (ans == -1)
{
ans=getchar();
}
return ans;
}
This uses the standard int function getchar() which reads the next character from the keyboard and returns its ASCII code or -1 if there isn't a key pressed. This function tends to vary in its behaviour according to the implementation you are using. Often it needs a carriage return pressed before it will return anything - so if you are using a different compiler and the program just hangs, try pressing "y" followed the by Enter or Return key.
The blines(n) function simply has to use a for loop to print the specified number of lines:
void blines(int n)
{
int i;
for(i=1 ; i<=n ; i++) printf("\n");
}
Last but not least are the functions to print the dot patterns. These are just boring uses of printf to show different patterns. Each function prints exactly three lines of dots and uses blank lines if necessary. The reason for this is that printing 25 blank lines should clear a standard text screen and after printing three lines printing 21 blank lines will scroll the pattern to the top of the screen. If this doesn't happen on your machine make sure you are using a 29 line text mode display.
void showone()
{
printf("\n * \n");
}
void showtwo()
{
printf(" * \n\n");
printf(" * \n");
}
void showthree()
{
printf(" * \n");
printf(" * \n");
printf(" *\n");
}
void showfour()
{
printf(" * * \n\n");
printf(" * * \n");
}
void showfive()
{
printf(" * * \n");
printf(" * \n");
printf(" * * \n");
}
void showsix()
{
int i;
for(i=1 ; i>=3 ; i++) printf(" * * \n");
}
The only excitement in all of this is the use of a for loop in showsix! Type this all in and add:
void showone();
void showtwo();
void showthree();
void showfour();
void showfive();
void showsix();
int randn();
char getans();
void blines();
before the main function if you type the other functions in after.
[program]
Once you have the program working try modifying it. For example, see if you can improve the look of the patterns. You might also see if you can reduce the number of showx functions in use - the key is that the patterns are built up of combinations of two horizontal dots and one centred dot. Best of luck.
Structure and Nesting
Objectives
This section brings together the various looping mechanisms available to the C programmer with the program control constructs we met in the last section.
We also demonstrates a neat trick with random numbers.
It is one of the great discoveries of programming that you can write any program using just simple while loops and if statements. You don't need any other control statements at all. Of course it might be nice to include some other types of control statement to make life easy - for example, you don't need the for loop, but it is good to have! So as long as you understand the if and the while loop in one form or another you can write any program you want to.
If you think that a loop and an if statement are not much to build programs then you are missing an important point. It's not just the statements you have, but the way you can put them together. You can include an if statement within a loop, loops within loops are also OK, as are loops in ifs, and ifs in ifs and so on. This putting one control statement inside another is called nesting and it is really what allows you to make a program as complicated as you like.
Think of a number
Now let's have a go at writing the following program: 'It thinks of a number in the range 0 to 99 and then asks the user to guess it'. This sounds complicated, especially the 'thinks of a number' part, but all you need to know is that the statement:
r = rand()
will store a random number in the integer variable r. The standard library function rand() randomly picks a number within the range 0 to 32767, but this might vary from machine to machine. Look upon rand() as being a large dice.
Our problem is to select a number between 0 and 99 and not between 0 and 32767. How can we get our random number to within our range? The rand() function will produce numbers such as:
2567
134
20678
15789
32001
15987
etc...
If you look at the last two digits of all of these numbers they would form our random set! To select just these numbers we can use an arithmetic calculation of the following form:
r = rand() % 100
That is, to get the number into the right range you simply take the remainder on dividing by 100, ie a value in the range 0 to 99. You should remember this neat programming trick, you'll be surprised how often it is required.
Our solution to the problem is as follows:
#include
main()
{
int target;
int guess;
int again;
printf("\n Do you want to guess a number 1 =Yes, 0=No ");
scanf("%d",&again);
while (again)
{
target = rand() % 100;
guess = target + l;
while(target!=guess)
{
printf('\n What is your guess ? ");
scanf("%d",&guess);
if (target>guess) printf("Too low");
else printf("Too high");
}
printf("\n Well done you got it! \n");
printf("\nDo you want to guess a number 1=Yes, 0=No");
scanf("%d".&again);
}
}
[program]
This looks like a very long and complicated program, but it isn't. Essentially it used two loops and an if/else which in English could be summarised as:
while(again) {
think of a number
while (user hasn't guessed it)
{
get users guess.
if (target < guess) tell the user the guess is low
else tell the user the guess is high
}
}
The integer variable again is used to indicate that the user wants to carry on playing. If it is 0 then the loop stops so 0 = No, and 1, or any other non-zero value, = Yes.
If you try this program out you will discover that it has a slight flaw - not so much a bug, more a feature. If the user guesses the correct value the program still tells the user that the guess is too high and then congratulates them that they have the correct value. Such problems with how loops end are common and you have to pay attention to details such as this. There are a number of possible solutions, but the most straight forward is to change the inner loop so that the first guess is asked for before the loop begins. This shifts the test for the loop to stop to before the test for a high or low guess:
#include
main()
{
int target;
int guess;
int again;
printf("\n Do you want to guess a number 1 =Yes, 0=No ");
scanf("%d",&again);
while (again)
{
target = rand() % 100;
printf('\n What is your guess ? ");
scanf("%d",&guess);
while(target!=guess)
{
if (target>guess) printf("Too low");
else printf("Too high");
printf('\n What is your guess ? ");
scanf("%d",&guess);
}
printf("\n Well done you got it! \n");
printf("\n Do you want to guess a number 1=Yes, 0=No");
scanf("%d".&again);
}
}
[program]
If you want to be sure that you understand what is going on here, ask yourself why the line:
guess = target + 1;
was necessary in the first version of the program and not in the second?
Conditional Execution
Objectives
Having read this section you should be able to:
1. Program control with if , if-else and switch structures
2. have a better idea of what C understands as true and false.
Program Control
It is time to turn our attention to a different problem - conditional execution. We often need to be able to choose which set of instructions are obeyed according to a condition. For example, if you're keeping a total and you need to display the message 'OK' if the value is greater than zero you would need to write something like:
if (total>O) printf("OK");
This is perfectly reasonable English, if somewhat terse, but it is also perfectly good C. The if statement allows you to evaluate a > condition and only carry out the statement, or compound statement, that follows if the condition is true. In other words the printf will only be obeyed if the condition total > O is true.
If the condition is false then the program continues with the next instruction. In general the if statement is of the following form:
if (condition) statement;
and of course the statement can be a compound statement.
Here's an example program using two if statements:
#include
main()
{
int a , b;
do {
printf("\nEnter first number: ");
scanf("%d" , &a);
printf("\nEnter second number: ");
scanf("%d" , &b);
if (a< 999); }
[program]
Here's another program using an if keyword and a compound statement or a block:
#include
main()
{
int a , b;
do {
printf("\nEnter first number: ");
scanf("%d" , &a);
printf("\nEnter second number: ");
scanf("%d" , &b);
if (a< 999); }
[program]
The if statement lets you execute or skip an instruction depending on the value of the condition. Another possibility is that you might want to select one of two possible statements - one to be obeyed when the condition is true and one to be obeyed when the condition is false. You can do this using the
if (condition) statement1;
else statement2;
form of the if statement.
In this case statement1 is carried out if the condition is true and statement2 if the condition is false.
Notice that it is certain that one of the two statements will be obeyed because the condition has to be either true or false! You may be puzzled by the semicolon at the end of the if part of the statement. The if (condition) statement1 part is one statement and the else statement2 part behaves like a second separate statement, so there has to be semi-colon terminating the first statement.
Logical Expressions
So far we have assumed that the way to write the conditions used in loops and if statements is so obvious that we don't need to look more closely. In fact there are a number of deviations from what you might expect. To compare two values you can use the standard symbols:
">" (greater than)
"<" (less than)
">=" (for greater than or equal to )
"<=" (for less than or equal to)
"==" (to test for equality)
The reason for using two equal signs for equality is that the single equals sign always means store a value in a variable - i.e. it is the assignment operator. This causes beginners lots of problems because they tend to write:
if (a = 10) instead of if (a == 10)
The situation is made worse by the fact that the statement if (a = 10) is legal and causes no compiler error messages! It may even appear to work at first because, due to a logical quirk of C, the assignment actually evaluates to the value being assigned and a non-zero value is treated as true (see below). Confused? I agree it is confusing, but it gets easier. . .
Just as the equals condition is written differently from what you might expect so the non-equals sign looks a little odd. You write not equals as !=. For example:
if (a != 0)
is 'if a is not equal to zero'.
An example program showing the if else construction now follows:
#include
main ()
{
int num1, num2;
printf("\nEnter first number ");
scanf("%d",&num1);
printf("\nEnter second number ");
scanf("%d",&num2);
if (num2 ==0) printf("\n\nCannot devide by zero\n\n");
else printf("\n\nAnswer is %d\n\n",num1/num2);
}
[program]
This program uses an if and else statement to prevent division by 0 from occurring.
True and False in C
Now we come to an advanced trick which you do need to know about, but if it only confuses you, come back to this bit later. Most experienced C programmers would wince at the expression if(a!=0).
The reason is that in the C programming language dosen't have a concept of a Boolean variable, i.e. a type class that can be either true or false. Why bother when we can use numerical values. In C true is represented by any numeric value not equal to 0 and false is represented by 0. This fact is usually well hidden and can be ignored, but it does allow you to write
if(a != 0) just as if(a)
because if a isn't zero then this also acts as the value true. It is debatable if this sort of shortcut is worth the three characters it saves. Reading something like
if(!done)
as 'if not done' is clear, but if(!total) is more dubious.
Using break and continue Within Loops
The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. When the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop. The break statement can be used with all three of C's loops. You can have as many statements within a loop as you desire. It is generally best to use the break for special purposes, not as your normal loop exit. break is also used in conjunction with functions and case statements which will be covered in later sections.
The continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process. In the case of the for loop, the increment part of the loop continues. One good use of continue is to restart a statement sequence when an error occurs.
#include
main()
{
int x ;
for ( x=0 ; x<=100 ; x++) { if (x%2) continue; printf("%d\n" , x); } }
[program]
Here we have used C's modulus operator: %. A expression:
a % b
produces the remainder when a is divided by b; and zero when there is no remainder.
Here's an example of a use for the break statement:
#include
main()
{
int t ;
for ( ; ; ) {
scanf("%d" , &t) ;
if ( t==10 ) break ;
}
printf("End of an infinite loop...\n");
}
[program]
Select Paths with switch
While if is good for choosing between two alternatives, it quickly becomes cumbersome when several alternatives are needed. C's solution to this problem is the switch statement. The switch statement is C's multiple selection statement. It is used to select one of several alternative paths in program execution and works like this: A variable is successively tested against a list of integer or character constants. When a match is found, the statement sequence associated with the match is executed. The general form of the switch statement is:
switch(expression)
{
case constant1: statement sequence; break;
case constant2: statement sequence; break;
case constant3: statement sequence; break;
.
.
.
default: statement sequence; break;
}
Each case is labelled by one, or more, constant expressions (or integer-valued constants). The default statement sequence is performed if no matches are found. The default is optional. If all matches fail and default is absent, no action takes place.
When a match is found, the statement sequence associated with that case are executed until break is encountered.
An example program follows:
#include
main()
{
int i;
printf("Enter a number between 1 and 4");
scanf("%d",&i);
switch (i)
{
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
default:
printf("unrecognized number");
} /* end of switch */
}
[program]
This simple program recognizes the numbers 1 to 4 and prints the name of the one you enter. The switch statement differs from if, in that switch can only test for equality, whereas the if conditional expression can be of any type. Also switch will work with only int and char types. You cannot for example, use floating-point numbers. If the statement sequence includes more than one statement they will have to be enclosed with {} to form a compound statement.
Control Loops
ObjectivesHaving read this section you should have an idea about C's:
Go With The FlowOur programs are getting a bit more sophisticated, but they still lack that essential something that makes a computer so necessary. Exactly what they lack is the most difficult part to describe to a beginner. There are only two great ideas in computing. The first is the variable and you've already met that. The second is flow of control.When you write a list of instructions for someone to perform you usually expect them to follow the list from the top to the bottom, one at a time. This is the simple default flow of control through a program. The C programs we have written so far use this one-after-another default flow of control. This is fine and simple, but it limits the running time of any program we can write. Why? Simply because there is a limit to the number of instructions you can write and it doesn't take long for a computer to read though and obey your list. So how is it that we have programs that run for hours on end if need be? The answer is statements that alter the one-after-another order of obeying instructions. Perhaps the most useful is the loop. Suppose we ask you to display "Hello World!" five times on the screen. Easy! you'd say:
Indeed, this does exactly what was asked. But now we up the bet and ask you to do the same job for 100 hellos or, if you're still willing to type that much code, maybe 1,000 Hello World's, 10,000 Hello World's, or whatever it takes you to realise this isn't a sensible method! What you really need is some way of repeating the printf statements without having to write it out each time. The solution to this problem is the while loop or the do while loop. The while and do while LoopsYou can repeat any statement using either the while loop:while(condition) compound statement; or the do while loop: do compound statement while(condition); The condition is just a test to control how long you want the compound statement to carry on repeating. Each line of a C program up to the semicolon is called a statement. The semicolon is the statement's terminator. The braces { and } which have appeared at the beginning and end of our program unit can also be used to group together related declarations and statements into a compound statement or a block. In the case of the while loop before the compound statement is carried out the condition is checked, and if it is true the statement is obeyed one more time. If the condition turns out to be false, the looping isn't obeyed and the program moves on to the next statement. So you can see that the instruction really means while something or other is true keep on doing the statement. In the case of the do while loop it will always execute the code within the loop at least once, since the condition controlling the loop is tested at the bottom of the loop. The do while loop repeats the instruction while the condition is true. If the condition turns out to be false, the looping isn't obeyed and the program moves on to the next statement. Conditions or Logical ExpressionsThe only detail we need to clear up is what the condition (or Logical Expression) can be. How, for example, do we display 100 or 10,000 "Hello World!" messages? The condition can be any test of one value against another. For example:a>0 is true if a contains a value greater than zero; b<0 is true if b contains a value less than zero. The only complication is that the test for 'something equals something else' uses the character sequence == and not =. That's right: a test for equality uses two equal-signs, as in a==0, while an assignment, as in a=0, uses one. This use of the double or single equal sign to mean slightly different things is a cause of many a program bug for beginner and expert alike! So what about answering the question? What about the 100 "Hello World"s? Well, for the moment we know easily how to produce an infinite number of Hello Worlds! using while loop: and using the do while loop: If you type either of these programs in and run it you will find that your screen fills with a never ending list of "Hello World!"s. Why? Because the condition to keep the repeat going is ( 1 == 1 ), one equals one in plain English, which is always true! So how do we stop the loop? In some cases it could be by pulling the plug out - but usually you can stop an infinite loop by pressing Ctrl-Break or Ctrl-C. An infinite loop is sometimes useful - I certainly hope the program controlling the nearest nuclear power station is an infinite loop that never receives a Ctrl-Break signal! Most loops, however, have to stop some time. To solve our problem of printing 100 "Hello World!"s we need a counter and a test for when that counter reaches 100. A counter is a simple variable that has one added to it each time through the loop, using an instruction like this: a=a+1; This always confuses beginners, because they aren't used to seeing the variable on both sides of the equal-sign. All this means is that a has one added to it to produce a new value, and this value is stored back in the location called a. If you're worried, try thinking about it as: The two approaches are more or less the same. C is a language where anything that's used often can be said concisely, so it lets you say "add one to a variable" using the shorter notation: ++a; The double plus is read "increment a by one". Make sure you know that ++a; and a=a+1; are the same thing because you will often see both in typical C programs. The increment operator ++ and the equivalent decrement operator --, can be used as either prefix (before the variable) or postfix (after the variable). Note: ++a increments a before using its value; whereas a++ which means use the value in a then increment the value stored in a. Now it is easy to print "Hello World!" 100 times using the while loop:
[program] or the do while loop:
[program] Note: the use of the { and } to form a compound statement; all statements between the braces will be executed before the loop check is made. The integer variable count is declared and then set to zero, ready to count the number of times we have gone round the loop. Each time round the loop the value of count is checked against 100. As long as it is less, the loop carries on. Each time the loop carries on, count is incremented and "Hello World!" is printed - so eventually count does reach 100 and the loop stops. These little programs are just a bit more subtle than you might think. Ask yourself, do they really print exactly 100 times? Ask yourself: what is the final value of count? If you want to make sure you are right change the printf to: printf("count is %d",count); and add a printf after the loop: printf("final value is %d",count); Make sure you understand why you get the results that you do. What would happen if you changed the initial value of count to be one rather than zero? Looping the LoopWe have seen that any list of statements enclosed in curly brackets is treated as a single statement, a compound statement. So to repeat a list of statements all you have to do is put them inside a pair of curly brackets as in:which repeats the list while the condition is true. Notice that the statements within the curly brackets have to be terminated by semicolons as usual. Notice also that as the while statement is a complete statement it too has to be terminated by a semi-colon - except for the influence of one other punctuation rule. You never have to follow a right curly bracket with a semi-colon. This rule was introduced to make C look tidier by avoiding things like };};};} at the end of a complicated program. You can write the semi-colon after the right bracket if you want to, but most C programmers don't. You can use a compound statement anywhere you can use a single statement. The for LoopThe while, and do-while, loop is a completely general way of repeating a section of program over and over again - and you don't really need anything else but... The while loop repeats a list of instructions while some condition or other is true and often you want to repeat something a given number of times.The traditional solution to this problem is to introduce a variable that is used to count the number of times that a loop has been repeated and use its value in the condition to end the loop. For example, the loop: repeats while i is less than 10. As the ++ operator is used to add one to i each time through the loop you can see that i is a loop counter and eventually it will get bigger than 10, i.e. the loop will end. The question is how many times does the loop go round? More specifically what values of i is the loop carried out for? If you run this program snippet you will find that it prints 1,2,3... and finishes at 10. That is, the loop repeats 10 times for values of i from 1 to 10. This sort of loop - one that runs from a starting value to a finishing value going up by one each time - is so common that nearly all programming languages provide special commands to implement it. In C this special type of loop can be implemented as a for loop. which is entirely equivalent to: The condition operator <= should be interpreted as less than or equal too. We will be covering all of C's conditions , or logical expressions, in the next section. For example to print the numbers 1 to 100 you could use: for ( i=l; i <= 100; ++i ) printf("%d \n",i); You can, of course repeat a longer list of instructions simply by using a compound statement. The C for loop is much more flexible than this simple description. Indeed, many would be horrified at the way we have described the for loop without displaying its true generality, but keep in mind that there is more to come. In the meantime consider the following program, it does a temperature conversion, but it also introduces one or two new concepts:
[program] and here's another one for you to look at:
[program]
|
Input and Output Functions
Objectives
Having read this section you should have a clearer idea of one of C's:
- input functions, called scanf
- output functions, called printf
On The Run
Even with arithmetic you can't do very much other than write programs that are the equivalent of a pocket calculator. The real break through comes when you can read values into variables as the program runs. Notice the important words here: "as the program runs". You can already store values in variables using assignment. That is:a=100;
stores 100 in the variable a each time you run the program, no matter what you do. Without some sort of input command every program would produce exactly the same result every time it was run. This would certainly make debugging easy! But in practice, of course, we need programs to do different jobs each time they are run. There are a number of different C input commands, the most useful of which is the scanf command. To read a single integer value into the variable called a you would use:
scanf("%d",&a);
For the moment don't worry about what the %d or the &a means - concentrate on the difference between this and:
a=100;
When the program reaches the scanf statement it pauses to give the user time to type something on the keyboard and continues only when users press
The final missing piece in the jigsaw is using the printf function, the one we have already used to print "Hello World", to print the value currently being stored in a variable. To display the value stored in the variable a you would use:
printf("The value stored in a is %d",a);
The %d, both in the case of scanf and printf, simply lets the compiler know that the value being read in, or printed out, is a decimal integer - that is, a few digits but no decimal point.
Note: the scanf function does not prompt for an input. You should get in the habit of always using a printf function, informing the user of the program what they should type, before a scanf function.
Input and Output Functions in More Detail
One of the advantages of C is that essentially it is a small language. This means that you can write a complete description of the language in a few pages. It doesn't have many keywords or data types for that matter. What makes C so powerful is the way that these low-level facilities can be put together to make higher level facilities.The only problem with this is that C programmers have a tendency to reinvent the wheel each time they want to go for a ride. It is also possible to write C programs in a variety of styles which depend on the particular tricks and devices that a programmer chooses to use. Even after writing C for a long time you will still find the occasionally construction which makes you think, "I never thought of that!" or, "what is that doing?"
One attempt to make C a more uniform language is the provision of standard libraries of functions that perform common tasks. We say standard but until the ANSI committee actually produced a standard there was, and still is, some variation in what the standard libraries contained and exactly how the functions worked. Having said that we had better rush in quickly with the reassurance that in practice the situation isn't that bad and most of the functions that are used frequently really are standard on all implementations. In particular the I/O functions vary very little.
It is now time to look at exactly how scanf and printf work and what they can do - you might be surprised at just how complex they really are!
The original C specification did not include commands for input and output. Instead the compiler writers were supposed to implement library functions to suit their machines. In practice all chose to implement printf and scanf and after a while C programmers started to think of them as if these functions were I/O keywords! It sometimes helps to remember that they are functions on a par with any other functions you may care to define. If you want to you can provide your own implementations of printf or scanf or any of the other standard functions - we'll discover how later.
printf
The printf (and scanf) functions do differ from the sort of functions that you will created for yourself in that they can take a variable number of parameters. In the case of printf the first parameter is always a string (c.f. "Hello World") but after that you can include as many parameters of any type that you want to. That is, the printf function is usually of the form:printf(string,variable,variable,variable...)
where the ... means you can carry on writing a list of variables separated by commas as long as you want to. The string is all-important because it specifies the type of each variable in the list and how you want it printed. The string is usually called the control string or the format string. The way that this works is that printf scans the string from left to right and prints on the screen, or any suitable output device, any characters it encounters - except when it reaches a % character. The % character is a signal that what follows it is a specification for how the next variable in the list of variables should be printed. printf uses this information to convert and format the value that was passed to the function by the variable and then moves on to process the rest of the control string and anymore variables it might specify. For example:
printf("Hello World");
only has a control string and, as this contains no % characters it results in Hello World being displayed and doesn't need to display any variable values. The specifier %d means convert the next value to a signed decimal integer and so:
printf("Total = %d",total);
will print Total = and then the value passed by >total as a decimal integer.
If you are familiar other programming languages then you may feel happy about the printf function because something like:
printf("Total = %d",total);
looks like the sort of output command you might have used before. For example, in BASIC you would write:
PRINT "Total = ",total
but the C view of output is at a lower level than you might expect. The %d isn't just a format specifier, it is a conversion specifier. It indicates the data type of the variable to be printed and how that data type should be converted to the characters that appear on the screen. That is %d says that the next value to be printed is a signed integer value (i.e. a value that would be stored in a standard int variable) and this should be converted into a sequence of characters (i.e. digits) representing the value in decimal. If by some accident the variable that you are trying to display happens to be a float or a double then you will still see a value displayed - but it will not correspond to the actual value of the float or double.
The reason for this is twofold.
- The first difference is that an int uses two bytes to store its value, while a float uses four and a double uses eight. If you try to display a float or a double using %d then only the first two bytes of the value are actually used.
- The second problem is that even if there wasn't a size difference ints, floats and doubles use a different binary representation and %d expects the bit pattern to be a simple signed binary integer.
This is all a bit technical, but that's in the nature of C. You can ignore these details as long as you remember two important facts:
- The specifier following % indicates the type of variable to be displayed as well as the format in which that the value should be displayed;
- If you use a specifier with the wrong type of variable then you will see some strange things on the screen and the error often propagates to other items in the printf list.
You can also add an 'l' in front of a specifier to mean a long form of the variable type and h to indicate a short form (long and short will be covered later in this course). For example, %ld means a long integer variable (usually four bytes) and %hd means short int. Notice that there is no distinction between a four-byte float and an eight-byte double. The reason is that a float is automatically converted to a double precision value when passed to printf - so the two can be treated in the same way. (In pre-ANSI all floats were converted to double when passed to a function but this is no longer true.) The only real problem that this poses is how to print the value of a pointer? The answer is that you can use %x to see the address in hex or %o to see the address in octal. Notice that the value printed is the segment offset and not the absolute address - to understand what we am going on about you need to know something about the structure of your processor.
The % Format Specifiers
The % specifiers that you can use in ANSI C are:Usual variable type Display
%c char single character
%d (%i) int signed integer
%e (%E) float or double exponential format
%f float or double signed decimal
%g (%G) float or double use %f or %e as required
%o int unsigned octal value
%p pointer address stored in pointer
%s array of char sequence of characters
%u int unsigned decimal
%x (%X) int unsigned hex value
Formatting Your Output
The type conversion specifier only does what you ask of it - it convert a given bit pattern into a sequence of characters that a human can read. If you want to format the characters then you need to know a little more about the printf function's control string.Each specifier can be preceded by a modifier which determines how the value will be printed. The most general modifier is of the form:
flag width.precision
The flag can be any of:
flag meaningThe width specifies the number of characters used in total to display the value and precision indicates the number of characters used after the decimal point.
- left justify
+ always display sign
space display space if there is no sign
0 pad with leading zeros
# use alternate form of specifier
For example, %10.3f will display the float using ten characters with three digits after the decimal point. Notice that the ten characters includes the decimal point, and a - sign if there is one. If the value needs more space than the width specifies then the additional space is used - width specifies the smallest space that will be used to display the value. (This is quiet reassuring, you won't be the first programmer whose program takes hours to run but the output results can't be viewed because the wrong format width has been specified!)
The specifier %-1Od will display an int left justified in a ten character space. The specifier %+5d will display an int using the next five character locations and will add a + or - sign to the value.
The only complexity is the use of the # modifier. What this does depends on which type of format it is used with:
%#o adds a leading 0 to the octal value
%#x adds a leading 0x to the hex value
%#f or
%#e ensures decimal point is printed
%#g displays trailing zeros
Strings will be discussed later but for now remember: if you print a string using the %s specifier then all of the characters stored in the array up to the first null will be printed. If you use a width specifier then the string will be right justified within the space. If you include a precision specifier then only that number of characters will be printed.
For example:
printf("%s,Hello")
will print Hello,
printf("%25s ,Hello")
will print 25 characters with Hello right justified and
printf("%25.3s,Hello")
will print Hello right justified in a group of 25 spaces.
Also notice that it is fine to pass a constant value to printf as in printf("%s,Hello").
Finally there are the control codes:
If you include any of these in the control string then the corresponding ASCII control code is sent to the screen, or output device, which should produce the effect listed. In most cases you only need to remember \n for new line.
\b backspace
\f formfeed
\n new line
\r carriage return
\t horizontal tab
\' single quote
\0 null
scanf
Now that we have mastered the intricacies of printf you should find scanf very easy. The scanf function works in much the same way as the printf. That is it has the general form:scanf(control string,variable,variable,...)
In this case the control string specifies how strings of characters, usually typed on the keyboard, should be converted into values and stored in the listed variables. However there are a number of important differences as well as similarities between scanf and printf.
The most obvious is that scanf has to change the values stored in the parts of computers memory that is associated with parameters (variables).
To understand this fully you will have to wait until we have covered functions in more detail. But, just for now, bare with us when we say to do this the scanf function has to have the addresses of the variables rather than just their values. This means that simple variables have to be passed with a preceding >&. (Note for future reference: There is no need to do this for strings stored in arrays because the array name is already a pointer.)
The second difference is that the control string has some extra items to cope with the problems of reading data in. However, all of the conversion specifiers listed in connection with printf can be used with scanf.
The rule is that scanf processes the control string from left to right and each time it reaches a specifier it tries to interpret what has been typed as a value. If you input multiple values then these are assumed to be separated by white space - i.e. spaces, newline or tabs. This means you can type:
3 4 5
or
3
4
5
and it doesn't matter how many spaces are included between items. For example:
scanf("%d %d",&i,&j);
will read in two integer values into i and j. The integer values can be typed on the same line or on different lines as long as there is at least one white space character between them.
The only exception to this rule is the %c specifier which always reads in the next character typed no matter what it is. You can also use a width modifier in scanf. In this case its effect is to limit the number of characters accepted to the width.
For example:
scanf("%lOd",&i)
would use at most the first ten digits typed as the new value for i.
There is one main problem with scanf function which can make it unreliable in certain cases. The reason being is that scanf tends to ignore white spaces, i.e. the space character. If you require your input to contain spaces this can cause a problem. Therefore for string data input the function getstr() may well be more reliable as it records spaces in the input text and treats them as an ordinary characters.
Custom Libraries
If you think printf and scanf don't seem enough to do the sort of job that any modern programmer expects to do, you would be right. In the early days being able to print a line at a time was fine but today we expect to be able to print anywhere on the screen at any time.The point is that as far as standard C goes simple I/O devices are stream-oriented - that is you send or get a stream of characters without any notion of being able to move the current position in the stream. If you want to move backwards and forwards through the data then you need to use a direct access file. In more simple terms, C doesn't have a Tab(X,Y) or Locate(X,Y) function or command which moves the cursor to the specified location! How are you ever going to write your latest block buster game, let alone build your sophisticated input screens?
Well you don't have to worry too much because although C may not define them as standard, all C implementations come with an extensive graphics/text function library that allows you to do all of this and more. Such a library isn't standard, however the principles are always the same. The Borland and Microsoft offerings are usually considered as the two facto standards.
Summing It Up
Now that we have arithmetic, a way of reading values in and a way of displaying them, it's possible to write a slightly more interesting program than "Hello World". Not much more interesting, it's true, but what do you expect with two instructions and some arithmetic?Let's write a program that adds two numbers together and prints the result. (I told you it wasn't that much more interesting!) Of course, if you want to work out something else like Fahrenheit to centigrade, inches to centimetres or the size of your bank balance, then that's up to you - the principle is the same.
The program is a bit more complicated than you might expect, but only because of the need to let the user know what is happening:
#include
main()
{
int a,b,c;
printf("\nThe first number is ");
scanf("%d",&a);
printf("The second number is ");
scanf("%d",&b);
c=a+b;
printf("The answer is %d \n",c);
}
[program]
The first instruction declares three integer variables: a, b and c. The first two printf statements simply display message on the screen asking the user for the values. The scanf functions then read in the values from the keyboard into a and b. These are added together and the result in c is displayed on the screen with a suitable message. Notice the way that you can include a message in the printf statement along with the value.
Type the program in, compile it and link it and the result should be your first interactive program. Try changing it so that it works out something a little more adventurous. Try changing the messages as well. All you have to remember is that you cannot store values or work out results greater than the range of an integer variable or with a fractional part.
