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

The example illustrates one style of writing a block in an if statement. This style matches { and } as

follows:

if (<condition>)

{

<statement1>;

<statement2>;

etc.

}

Here, { and } line up with if and the statements are indented. This makes it easy to recognize

what’s in the body. For a small program, it probably doesn’t matter, but as program size increases,

it will become more important for the layout of the code to reflect its structure. In this book, we will

use the following style (as you would know by now, the compiler doesn’t care which style is used):

if (<condition>) {

<statement1>;

<statement2>;

etc.

}

We will put { on the first line after the right bracket and let } match up with if; the statements

in the block are indented. We believe this is as clear as the first style and it’s one less line in the

program! Which style you use is a matter of personal preference; choose one and use it consistently.

4.3.1 Find the Sum of Two Lengths

Suppose that a length is given in meters and centimeters, for example, 3m 75cm. You are given

two pairs of integers representing two lengths. Write a program to prompt for two lengths and

print their sum such that the centimeter value is less than 100.

For example, the sum of 3m 25cm and 2m 15cm is 5m 40cm, but the sum of 3m 75cm and

5m 50cm is 9m 25cm.

Assume the program works as follows:

Enter values for m and cm: 3 75

Enter values for m and cm: 5 50

Sum is 9m 25cm

Observe that the data must be entered with digits only. If, for instance, we type 3m 75cm we will

get an error since 3m is not a valid integer constant. Our program will assume that the first number

entered is the meter value and the second number is the centimeter value.

72

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!