Test and debug the program
Having written the program, the next job is to test it to find out whether it is doing its intended job. Testing a program involves the following steps:
1. compile the program: a computer can only execute a program written in machine language. Before the computer can run our C program, the latter must be converted to machine language. We say that the source code must be converted to object code or machine code. The program which does this job is called a compiler.
Among other things, a compiler will check the source code for syntax errors—errors which arise from breaking the rules for writing statements in the language. For example, a common syntax error in writing C programs is to omit a semicolon or to put one where it is not required.
If the program contains syntax errors, these must be corrected before compiling it again. When the program is free from syntax errors, the compiler will convert it to machine language and we can go on to the next step.
2. run the program: here we request the computer to execute the program and we supply data to the program for which we know the answer. Such data is called test data. Some values we can use for the length of a side are 3, 12 and 20.
If the program does not give us the answers 9, 144 and 400, respectively, then we know that the program contains at least one logic error. A logic error is one which causes a program to give incorrect results for valid data. A logic error may also cause a program to crash (come to an abrupt halt).
If a program contains logic errors, we must debug the program—we must find and correct any errors that are causing the program to produce wrong answers.
To illustrate, suppose the statement which calculates the area was written (incorrectly) as:
a = s + s;
and when the program is run, 10 is entered for the length. We know that the area should be 100. But when we run the program, we get:
Enter length of side: 10
Area of square is 20
Since this is not the answer we expect, we know that there is an error (perhaps more than one) in the program. Since the area is wrong, the logical place to start looking for the error is in the statement which calculates the area. If we look closely, we should discover that + was typed instead of *. When this correction is made, the program works fine.