Previous: 2.1.1 Developing the Algorithm
Up: 2.1 A Simple C Program
Next: 2.1.3 Running the Program
Previous Page: 2.1.1 Developing the Algorithm
Next Page: 2.1.3 Running the Program
A program in a high level language, such as C, is called a source program or source code. ( Code is a generic term used to refer to a program or part of a program in any language, high or low level). A program is made up of two types of items: data and procedures. Data is information we wish to process and is referred to using its name. Procedures are descriptions of the required steps to process the data and are also given names. In C, all procedures are called functions. A program may consist of one or more functions, but it must always include a function called main. This special function, main(), acts as a controller; directing all of the steps to be performed and is sometimes called the driver. The driver, like a conductor or a coordinator, may call upon other functions to carry out subtasks. When we refer to a function in the text, we will write its name followed by parentheses, e.g. main(), to indicate that this is the name of a function.
The program that implements the above algorithm in C is shown in Figure 2.1. Let us first look briefly at what the statements in the above program do during execution.
Any text between the markers, /* and */ is a comment or an explanation; it is not part of the program and is ignored by the compiler. However, comments are very useful for someone reading the program to understand what the program is doing. We suggest you get in the habit of including comments in your programs right from the first coding. The first few lines between /* and */ are thus ignored, and the actual program starts with the function name, main(). Parentheses are used in the code after the function name to list any information to be given to the function, called arguments. In this case, main() has no arguments. The body of the function main() is a number of statements between braces { and }, each terminated by a semi-colon.
The first two statements declare variables and their data types: id_number is an integer type, and hours_worked, rate_of_pay, and pay are floating point type. These statements indicate that memory should be allocated for these kinds of data and gives names to the allocated locations. The next statement writes or prints the title of the program on the screen.
The next three statements set the variables id_number, hours_worked, and rate_of_pay to some initial values: id_number is set to 123, hours_worked to 20.0, and rate_of_pay to 7.5. The next statement sets the variable pay to the product of the values of hours_worked and rate_of_pay. Finally, the last three statements print out the initial data values and the value of pay.