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

We find the sum by adding the two meter values and adding the two centimeter values. If the

centimeter value is less than 100, there is nothing more to do. But if it is not, we must subtract 100

from it and add 1 to the meter value. This logic is expressed as follows:

m = sum of meter values

cm = sum of centimeter values

if cm >= 100 then

subtract 100 from cm

add 1 to m

endif

As a boundary case, we must check that our program works if cm is exactly 100. As an exercise,

verify that it does.

Program P4.2 solves the problem as described.

Program P4.2

//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) {

cmSum = cmSum - 100;

mSum = mSum + 1;

}

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

}

We use the variables m1 and cm1 for the first length, m2 and cm2 for the second length, and mSum

and cmSum for the sum of the two lengths.

The program assumes that the centimeter part of the given lengths is less than 100 and it

works correctly if this is so. But what if the lengths were 3m 150cm and 2m 200cm?

The program will print 6m 250cm. (As an exercise, follow the logic of the program to see why.)

While this is correct, it is not in the correct format since we require the centimeter value to be

less than 100. We can modify our program to work in these cases as well by using integer division

and % (the remainder operator).

73

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!