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 astute reader may recognize that we do not even need the if statement.

Consider this:

mSum = m1 + m2; //add the meters

cmSum = cm1 + cm2; //add the centimeters

mSum = mSum + cmSum / 100;

cmSum = cmSum % 100;

where the last two statements come from the if statement.

We know therefore that this will work if cmSum is greater than or equal to 100 since, when that

is the case, these four statements are executed.

What if cmSum is less than 100? Originally, the last two statements would not have been

executed since the if condition would have been false. Now they are executed. Let us see what

happens. Using the example of 3m 25cm and 2m 15cm, we get mSum as 5 and cmSum as 40.

In the next statement 40 / 100 is 0 so mSum does not change and in the last statement

40 % 100 is 40 so cmSum does not change. So the answer will be printed correctly as

Sum is 5m 40cm

You should begin to realize by now that there is usually more than one way to express the logic of

a program. With experience and study, you will learn which ways are better and why.

4.4 The if...else Construct

Let us write a program for the following problem:

A student is given 3 tests, each marked out of 100. The student passes if his average mark is

greater than or equal to 50 and fails if his average mark is less than 50. Prompt for the 3 marks and

print Pass if the student passes and Fail if he fails.

We will write the program assuming it works as follows:

Enter 3 marks: 60 40 56

Average is 52.0 Pass

or

Enter 3 marks: 40 60 36

Average is 45.3 Fail

The following algorithm describes the steps required to solve the problem:

prompt for the 3 marks

calculate the average

if average is greater than or equal to 50 then

print "Pass"

else

print "Fail"

endif

75

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!