08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 1 ■ Elementary Programming Concepts

1.2.5 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: recall that a computer can execute a program written

in machine language only. 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 that does this job is called a compiler. Appendix D tells you how

you can acquire a C compiler for writing and running your programs.

2. Among other things, a compiler will check the source code for syntax

errors—errors that 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.

3. 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.

4. 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.

5. 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 that 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).

6. 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 that calculates the area was written (incorrectly) as:

a = s + s;

and when the program is run, 10 is entered for the length. (Below, 10 is underlined to indicate it is

typed by the user.) Assume we know that the area should be 100. But when the program is run, it

prints this:

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 that calculates the area. If we look closely, we should discover that + was typed instead

of *. When this correction is made, the program works fine.

8

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!