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 3 ■ Programs with Sequence Logic

Next, we need variables to store the interest and service charge. Since these may contain a

decimal point, we must use double variables—we call them interest and service.

Prompting for and reading the data are fairly straightforward, given what we have covered

so far. We need only emphasize that when numeric data is being entered, it must be a numeric

constant. We cannot, for instance, enter the average balance as $2500 or as 2,500. We must enter

it as 2500 or 2500.0 or 2500.00.

The calculation of the interest and service charge presents the biggest challenge. We must

specify the calculation in a form that the computer can understand and execute.

We cannot, for instance, write

interest = 6% of avgBalance;

or even

interest = 6% * avgBalance;

or

service = 50 cents per transaction;

We must express each right-hand side as a proper arithmetic expression, using appropriate

constants, variables, and operators. Therefore, “6% of average balance” must be expressed as

avgBalance*0.06

or

0.06*avgBalance

and “50 cents per transaction” must be expressed as

0.50*numTrans

or

numTrans*0.5

or something similar, even

numTrans/2.0

Printing the output is fairly straightforward. Even though, for example, we cannot use $ when

entering data for average balance, we can print a dollar sign in front of it when we print its value.

All we need to do is print $ as part of a string. How this is done is shown in the program. Similarly,

we print the interest and service charge labeled with a dollar sign.

We use the specification %3.2f for printing avgBalance. We intentionally use a small field

width of 3 so that avgBalance is printed using only the exact number of print columns needed

for printing its value. This ensures that its value is printed right next to the dollar sign. Similar

remarks apply to interest and service.

59

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!