The basic language elements are most easily illustrated with examples. Our first example just prints a friendly greeting:
|
/* /examples/chapter1/hello.c */
#include <stdio.h>
int main(void) {
printf("Hello from CATSL!");
return 0;
}
|
/* and continues
until the next */ is found (it could extend over several lines).
The next line gives access to the standard input-output library, which
is necessary to use the printf function. The next line is blank
for clarity (blank lines and spaces can be inserted liberally to make
programs easier to read).
The rest of the file defines a function called main. This is the
function which will be called when the program starts executing.
Observe that main is defined as returning an integer value (the
int keyword), it takes no arguments (the (void)) and that the
body of the function is contained between curly brackets, { and
}. Inside main we have two statements: first we print the
greeting, which ends with a newline character (the \n is
interpreted as a newline), and then we return a value of 0 (it is
normal for main to return 0 if the program doesn't encounter any
errors).
A few important rules are obeyed by our program:
printf with Printf and
the program will not work),
printf is a function (it returns an int),
we can ignore its return value. C lets you ignore the return from any
function; used in this way, printf behaves much like a
procedure in Pascal.
Time for a more complex example. Our next program prompts the user for a number, and then computes the volume of the sphere with that radius.
|
/* Compute the volume of a sphere, given the radius
/examples/chapter1/sphere.c */
#include <stdio.h>
#define PI 3.14159265358979323846
int main(void) {
float r, vol;
do {
printf("Enter radius (0 to quit): ");
scanf("%f",&r);
vol = 4.0*PI*r*r*r/3.0;
printf("radius = %fvolume = %f",r,vol);
} while (r > 0);
return 0;
}
|
#define statement. In main we declare the
variables r and vol as storing floats (a kind of
floating-point number). Variables must be declared before they are
used, and at the start of a `compound-statement' (the curly brackets define the
start and end of a compound-statement).
We use a do-while loop to let the user calculate the volume of
several spheres without having to re-run the program. Within the loop
we prompt the user for the radius with printf, read it in with
scanf (we'll describe scanf in more detail shortly),
calculate the volume and write out the answer. Note that assignment is
a simple = in C, rather than := as in Pascal.
To read in the radius, we use the function
scanf. The first argument, the string, tells
scanf how to interpret what the user types (the %f
indicates we want a single floating-point number and asks for the
number to be stored in a float variable), while the second,
&r tells scanf to put the answer in r.
To write out the answer, we again use printf, but this time with
three arguments. The first is the `format string', which is mostly
just copied to the screen (note the \n newline characters),
except for the %f sequences which printf replaces, in
turn, with the value of the other arguments: the first %f is
replaced with the value of r, and the second with the value
of vol.
The entire compound-statement between the curly brackets after the do keyword
is repeated until the while condition fails, i.e. until the user
enters a non-positive radius (note that the program will still
write out the radius and volume when this happens because the
while condition is only checked at the bottom of the compound-statement).
Unlike Pascal, the brackets in the while statement around the
continuation condition, r > 0, are required in C.
We finish with a more complex example, which contains almost everything required to a really useful C program.
|
/* Use binary section to locate cube-roots
/examples/chapter1/cube_root.c */
#include <stdio.h>
float f(float x) {
return x*x*x;
}
int main(void) {
float guess, f_guess;
float cube;
float lower_bound, upper_bound;
int iter, max_iters;
printf("Enter maximum number of iterations: ");
scanf("%d", &max_iters);
printf("Enter number to cube-root: ");
scanf("%f", &cube);
lower_bound = 0;
upper_bound = 100;
iter = 0;
while (iter <= max_iters) {
guess = 0.5*(lower_bound + upper_bound);
f_guess = f(guess);
printf("Iteration %d: ",iter);
printf("guess = %f, f(guess) = %f",guess,f_guess);
if (f_guess < cube) {
lower_bound = guess;
} else {
upper_bound = guess;
}
if (upper_bound - lower_bound < 5e-7) {
/* We may aswell stop here */
return 0;
}
iter = iter+1;
}
return 0;
}
|
f as well as main.
This function takes a single float argument and returns a
float, its cube. It is worth pointing out that as soon as the
return statement in f executes, the function will return:
any statements inside f after the return statement (here there
happen to be none) would never be executed. In main, we declare
the variables iter and max_iters to be ints (the
normal integer type). These must be handled differently from
floats in scanf and printf statements. Where with
floats we used %f, ints need %d.
Rather than a do-while loop, here we have used a while loop.
The only significant difference is that the continuation condition
(iter <= max_iters) is tested before the compound-statement is executed,
rather than at the end.
We also use an if-else construction to adjust the bounds
according to whether the the cube root lies to the left or right side
of the current guess.