Structure of a C program

advertisement
Structure of a C program
The syntax of a complete C program is given below:
. . .
int main()
{
. . .
return 0;
}
. . .
The meaning of the statements int main() and return will become clear later on.
Preprocessor statements (e.g., #define and #include statements) are conventionally
placed before the int main() statement. All executable statements must be placed
between the int main() and return statements. Function definitions (see later) are
conventionally placed after the return statement.
A simple C program (quadratic.c) that calculates the real roots of a quadratic
equation using the well-known quadratic formula is listed below.
/* quadratic.c */
/*
Program to evaluate real roots of quadratic equation
2
a x
+ b x + c = 0
using quadratic formula
2
x = ( -b +/- sqrt(b - 4 a c) ) / (2 a)
*/
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, d, x1, x2;
/* Read input data */
printf("\na = ");
scanf("%lf", &a);
printf("b = ");
scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
/* Perform calculation */
d = sqrt(b * b - 4. * a * c);
x1 = (-b + d) / (2. * a);
x2 = (-b - d) / (2. * a);
/* Display output */
printf("\nx1 = %12.3e
x2 = %12.3e\n", x1, x2);
return 0;
}
Note the use of comments (which are placed between the delimiters /* and */) to first
explain the function of the program and then identify the program's major sections.
Note, also, the use of indentation to highlight the executable statements. When
executed, the above program produces the following output:
a = 2
b = 4
c = 1
x1 =
-2.929e-01
x2 =
-1.707e+00
Of course, the 2, 4, and 1 were entered by the user in response to the programs's
prompts.
It is important to realize that there is more to writing a complete computer program
than simply arranging the individual declarations and statements in the right order.
Attention should also be given to making the program and its output as readable as
possible, so that the program's function is immediately obvious to other people. This
can be achieved by judicious use of indentation and whitespace, as well as the
inclusion of comments, and the generation of clearly labeled output. It is hoped that
this approach will be exemplified by the example programs used in this course.
Richard Fitzpatrick 2006-03-29
Download