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 4 ■ Programs with Selection Logic

The latest C99 standard defines the type bool. However, in this book, we will use the traditional

approach mainly because many popular C compilers do not support the C99 standard as yet. Also,

as you will see, we can easily live without bool. The vast majority of our Boolean expressions would

be relational expressions used in if and while statements. If we ever need a “Boolean” variable, we

can use an int variable with 1 representing true and 0 representing false.

4.3 The if Construct

Let us write a program for the following problem:

A computer repair shop charges $100 per hour for labor plus the cost of any parts used in the

repair. However, the minimum charge for any job is $150. Prompt for the number of hours worked

and the cost of parts (which could be $0) and print the charge for the job.

We will write the program so that it works as follows:

Hours worked? 2.5

Cost of parts? 20

Charge for the job: $270.00

or

Hours worked? 1

Cost of parts? 25

Charge for the job: $150.00

The following algorithm describes the steps required to solve the problem:

prompt for and read the hours worked

prompt for and read the cost of parts

calculate charge = hours worked * 100 + cost of parts

if charge is less than 150 then set charge to 150

print charge

This is another example of an algorithm written in pseudocode—an informal way of specifying

programming logic.

The algorithm introduces a new statement—the if statement. The expression

charge is less than 150

is an example of a condition. If the condition is true, the statement after then (called the then part)

is executed; if it is false, the statement after then is not executed.

Program P4.1 shows how to express this algorithm as a C program.

69

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!