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

And if hours is 50 and rate is 12 dollars per hour, regular pay is $480 (40 times 12) and overtime

pay is $180 (excess hours 10 times 12 times 1.5). Gross pay is $660 (480 + 180).

The above description could be expressed in pseudocode as follows:

if hours is less than or equal to 40 then

set regular pay to hours x rate

set overtime pay to 0

else

set regular pay to 40 x rate

set overtime pay to (hours – 40) x rate x 1.5

endif

set gross pay to regular pay + overtime pay

We use indentation to highlight the statements to be executed if the condition “hours is less than

or equal to 40” is true and those to be executed if the condition is false. The whole construct is

terminated with endif.

The next step is to convert the pseudocode to C. When we do, we have to make sure that we

stick to C’s rules for writing an if...else statement. In this example, we have to ensure that both

the then and else parts are written as blocks since they both consist of more than one statement.

Using the variables hours (hours worked), rate (rate of pay), regPay (regular pay), ovtPay

(overtime pay), and grossPay (gross pay), we write the C code, thus:

if (hours <= 40) {

regPay = hours * rate;

ovtPay = 0;

} //no semicolon here; } ends the block

else {

regPay = 40 * rate;

ovtPay = (hours - 40) * rate * 1.5;

} //no semicolon here; } ends the block

grossPay = regPay + ovtPay;

Note the two comments. It would be wrong to put a semicolon after the first } since the if

statement continues with an else part. If we were to put one, it effectively ends the if statement

and C assumes there is no else part. When it finds the word else, there will be no if with which

to match it and the program will give a “misplaced else” error.

There is no need for a semicolon after the last } but putting one would do no harm.

Problem: Write a program to prompt for hours worked and rate of pay. The program then

calculates and prints regular pay, overtime pay, and gross pay, based on the above description.

The following algorithm outlines the overall logic of the solution:

prompt for hours worked and rate of pay

if hours is less than or equal to 40 then

set regular pay to hours x rate

set overtime pay to 0

78

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!