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

Program P4.1

//print job charge based on hours worked and cost of parts

#include <stdio.h>

int main() {

double hours, parts, jobCharge;

printf("Hours worked? ");

scanf("%lf", &hours);

printf("Cost of parts? ");

scanf("%lf", &parts);

jobCharge = hours * 100 + parts;

if (jobCharge < 150) jobCharge = 150;

printf("\nCharge for the job: $%3.2f\n", jobCharge);

}

For this program, we choose to use three variables—hours, parts and jobCharge, all of type

double since we may need to enter floating-point values for hours worked and cost of parts.

It is very important that you make an extra effort to understand the if statement since it is

one of the most important statements in programming. It is the if statement that can make a

program appear to think.

The condition

charge is less than 150

of the pseudocode algorithm is expressed in our program as

jobCharge < 150

When the program is executed, the job charge is calculated in the normal way (hours * 100

+ parts). The if statement then tests if this value, jobCharge, is less than 150; if it is, then

jobCharge is set to 150. If it is not less than 150, jobCharge remains as it is. The statement

if (jobCharge < 150) jobCharge = 150;

is a simple example of the if construct. Observe that the word then is not used in C. In general,

the construct takes the following form in C:

if (<condition>) <statement>

The word if and the brackets around <condition> are required by C. You must supply

<condition> and <statement> where <condition> is a Boolean expression and <statement>

can be either a one-line statement or a block—one or more statements enclosed by { and }.

If <condition> is true, <statement> is executed; if <condition> is false, <statement> is not

executed. In either case, the program continues with the statement, if any, after <statement>.

70

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!