08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 ■ Programs with Selection Logic

For example, the pre-processing step changes

if (jobCharge < MinJobCost) jobCharge = MinJobCost;

to

if (jobCharge < 150) jobCharge = 150;

Suppose, for instance, that the minimum job cost changes from 150 to 180. We would just need to

change the value in the #define directive, thus:

#define MinJobCost 180

No other changes would be needed.

In this book, we will use the convention of starting a symbolic constant identifier with an

uppercase letter. Note, however, that C allows you to use any valid identifier.

4.6.2 Example – Symbolic Constants

For a slightly bigger example, consider program P4.5. There, we used two constants—40 and

1.5—denoting the maximum regular hours and the overtime rate factor, respectively. We rewrite

program P4.5 as program P4.7 using the symbolic constants MaxRegularHours (set to 40) and

OvertimeFactor (set to 1.5).

Program P4.7

#include <stdio.h>

#define MaxRegularHours 40

#define OvertimeFactor 1.5

int main() {

double hours, rate, regPay, ovtPay, grossPay;

printf("Hours worked? ");

scanf("%lf", &hours);

printf("Rate of pay? ");

scanf("%lf", &rate);

if (hours <= MaxRegularHours) {

regPay = hours * rate;

ovtPay = 0;

}

else {

regPay = MaxRegularHours * rate;

ovtPay = (hours - MaxRegularHours) * rate * OvertimeFactor;

}

grossPay = regPay + ovtPay;

printf("\nRegular pay: $%3.2f\n", regPay);

printf("Overtime pay: $%3.2f\n", ovtPay);

printf("Gross pay: $%3.2f\n", grossPay);

}

82

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!