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 following pseudocode shows how:

m = sum of meter values

cm = sum of centimeter values

if cm >= 100 then

add cm / 100 to m

set cm to cm % 100

endif

Using the above example, m is set to 5 and cm is set to 350. Since cm is greater than 100, we work

out 350 / 100 (this finds how many 100s there are in cm ) which is 3, using integer division; this

is added to m, giving 8. The next line sets cm to 350 % 100, which is 50. So the answer we get is 8m

50cm, which is correct and in the correct format.

Note that the statements in the “then part” must be written in the order shown. We must use

the (original) value of cm to work out cm / 100 before changing it in the next statement to cm % 100.

As an exercise, work out what value will be computed for the sum if these statements are reversed.

(The answer will be 5m 50cm, which is wrong. Can you see why?)

These changes are reflected in Program P4.3.

Program P4.3

//find the sum of two lengths given in meters and cm

#include <stdio.h>

int main() {

int m1, cm1, m2, cm2, mSum, cmSum;

printf("Enter values for m and cm: ");

scanf("%d %d", &m1, &cm1);

printf("Enter values for m and cm: ");

scanf("%d %d", &m2, &cm2);

mSum = m1 + m2; //add the meters

cmSum = cm1 + cm2; //add the centimeters

if (cmSum >= 100) {

mSum = mSum + cmSum / 100;

cmSum = cmSum % 100;

}

printf("\nSum is %dm %dcm\n", mSum, cmSum);

}

The following is a sample run of this program:

Enter values for m and cm: 3 150

Enter values for m and cm: 2 200

Sum is 8m 50cm

74

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!