Chapter 3 programming solutionshttp://www.scribd.com/doc/140655214...

Author:
Kilo batates

97 downloads 674 Views 1MB Size

SOLUTIONS 3.11

Identify and correct the errors in each of the following [ Note: There may be more than one error in each piece of code]: a) if ( age >= 65 ); printf( "Age is greater than or equal to 65\n" ); else printf( "Age is less than 65\n" ); ANS: if ( age >= 65 ) /* ; removed */ printf( “Age is greater than or equal to 65\n” ); else printf( “Age is less than 65\n” ); b) int x = 1, total; while ( x <= 10 ) { total += x; ++x; } ANS: int x = 1, total = 0; while ( x <= 10 ) { total += x; ++x; } c) While ( x <= 100 ) total += x; ++x; ANS: while ( x <= 100 ) { total += x; ++x; } d) while ( y > 0 ) { printf( "%d\n" "%d\n", , y ); ++y; } © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

20

Structured Program Development in C: Solutions

Chapter 3

ANS: while ( y > 0 ) { printf( “%d\n” “%d\n”, , y ); --y; } 3.12

3.13

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

Fill in the blanks in each of the following: a) The solution solution to any problem problem involves involves performing performing a series series of actions actions in a specific specific . ANS: order. b) A synonym synonym for proce procedure dure is . ANS: algorithm c) A variable variable that accumula accumulates tes the sum of several several numbers numbers is a . ANS: total. d) The process of setting certain variables to specific values at the beginning of a program is called . ANS: initialization. e) A special special value value used to indicate indicate “end of data entry” is called called a , a , a or a value. ANS: sentinel value, dummy value, signal value, flag value. f) A is a graphical graphical representa representation tion of an algorithm. algorithm. ANS: flowchart. g) In a flowchart, flowchart, the order in which the steps should be performed performed is indicated indicated by symbols. symbols. ANS: arrow (flowline). h) The terminatio termination n symbol indicates indicates the and of every algorithm. algorithm. ANS: beginning, end. i) Rectangle symbols correspond to calculations that are normally performed by statements and input/output oper operat atio ions ns that that are are norm normal ally ly perf perfor orme med d by call callss to the the and and stan standa dard rd libr libraary func functi tion ons. s. ANS: assignment, printf, scanf. j) The item written written inside a decision decision symbol is called a . ANS: condition. What does the following program print? #include

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 21

Chapter 3

1 4 9 16 25 36 49 64 81 100 Total is 385

3.14

Write a single pseudocode statement that indicates each of the following: a) Disp Displa lay y the the mess messag agee "Enter two numbers" . ANS: print “enter “enter two numbers” b) Assign Assign the the sum sum of varia variable bless x, y, and z to variable p. ANS: p = x + y + y + z c) The followin following g conditio condition n is to be tested tested in in an if…else selection statement: statement: The current value of variable m is greater than twice the current value of variable v. ANS: if m is greater than twice v do this ... else do this ... d) Obtain Obtain valu values es for for variabl variables es s, r, and t from the keyboard. ANS: input s , input r , input t

3.15

Formulate a pseudocode algorithm for each of the following: a) Obtain two numbers from the keyboard, compute the sum of the numbers and display the result. ANS: Input the first number number Input the second number number Add the two numbers numbers Output the sum b) Obtain two numbers numbers from the keyboard, keyboard, and determine and display which which (if either) either) is the larger of the the two numbers. ANS: Input the first number number from the the keyboard keyboard Input the second number number from from the keyboard keyboard If the first number is greater than the second second number number print it Else if the second number number is greater greater than than the first number print it Else print a message message stating stating that the the numbers numbers are equal equal c) Obtain a series of positive numbers from the keyboard, and and determine and display the sum of the numbers. Assume Assume that the user types the sentinel value -1 to indicate “end of data entry.” ANS: Input a value value from the keyboard keyboard While the input value is not equal to -1 add the number to the running total input the next number Print the sum

3.16

State which of the following are true and which are false. If a statement is false, explain why. a) Experience has shown that the most difficult part of solving a problem on a computer is producing producing a working C program. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

22

Structured Program Development in C: Solutions

Chapter 3

ANS: False. The algorithm is the hardest of solving a problem. b) A sentinel value must be a value that cannot be confused with a legitimate legitimate data value. value. ANS: True. c) Flowlines Flowlines indicat indicatee the action actionss to be performe performed. d. ANS: False. Flowlines indicate the order in which steps are performed. d) Conditions written inside decision decision symbols always contain contain arithmetic arithmetic operators operators (i.e., +, -, *, /, and %). ANS: False. They normally contain conditional operators. e) In top-down, stepwise stepwise refinement, refinement, each refinement is is a complete representation representation of the algorithm. algorithm. ANS: True. For Exercises 3.17 to 3.21, perform each of these steps:

1. Read the problem problem state statement. ment. 2. Formulate the algorithm using pseudocode and top-down, stepwise refinement. 3. Writ Writee a C prog progra ram. m. 4. Test, Test, debug, debug, and execut executee the C program program.. 3.17

Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several tankfuls of gasoline by recording miles driven and gallons used for each tankful. Develop a program that will input the miles driven and gallons used for each tankful. The program should calculate and display the miles per gallon obtained for each tankful. After processing all input information, the program should calculate and print the combined miles per gallon obtained for all tankfuls. Here is a sample input/output dialog:.

Enter the gallons used (-1 to end): 12.8 Enter the miles driven: 287 The miles / gallon for this tank was 22.421875 Enter the gallons used (-1 to end): 10.3 Enter the miles driven: 200 The miles / gallon for this tank was 19.417475 Enter the gallons used (-1 to end): 5 Enter the miles driven: 120 The miles / gallon for this tank was 24.000000 Enter the gallons used (-1 to end): -1 The overall average miles/gallon miles/gallon was 21.601423

ANS: 2)

Top: Determine the average miles/gall Determine miles/gallon on for each tank tank of gas, and and the overall miles/ga miles/gallon llon for for an arbitrary number of tanks of gas First refinement: Initialize variables variables Input the gallons used used and the the miles driven, driven, and calculat calculatee and print print the miles/gallon miles/gallon for each tank tank of gas. gas. Keep track of the total miles and the total gallons. Calculate and print the overall average miles/gallon. Second refinement: Initialize totalGal totalGallons lons to zero. zero. Initialize totalMil totalMiles es to zero. Input the gallons used for the the first tank. tank. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 23

Chapter 3

While the sentinel value (-1) has not been entered for the gallons Add gallons gallons to the running total in totalGal totalGallons lons Input the miles driven driven for the current tank tank Add miles to the running running total total in totalMiles totalMiles Calculate and print the miles/gallon Input the gallons used used for the next tank tank Set totalAverage to totalMiles divided by totalGallons. print the the average miles/gall miles/gallon on

3) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

/* Exercise 3.17 Solution */ #include

/* /* /* /* /*

gallons used for current tank*/ miles driven for current tank*/ total gallons used */ total miles driven */ average miles/gallon */

/* get gallons used for first tank */ printf( "Enter the gallons used ( -1 to end): " ); scanf( "%lf" "%lf", , &gallons ); /* loop until sentinel value read from user */ while ( gallons != -1.0 ) { totalGallons += gallons; /* add current tank gallons to total */ printf( "Enter the miles driven: " ); /* get miles driven */ scanf( "%lf" "%lf", , &miles ); totalMiles += miles; /* add current tank miles to total */ /* display miles per gallon for current tank */ printf( "The Miles / Gallon for this tank was %f\n\n", %f\n\n", miles / gallons ); /* get next tank's gallons */ printf( "Enter the gallons used ( -1 to end ): " ); scanf( "%lf" "%lf", , &gallons ); } /* end while */ /* calculate average miles per gallon over all tanks */ totalAverage = totalMiles / totalGallons; printf( "\nThe overall average Miles/Gallon was %f\n", %f\n", totalAverage ); return 0; /* indicate successful termination */ } /* end main */

3.18

Develop a C program that will determine if a department store customer has exceeded the credit limit on a charge account. For each customer, the following facts are available: 1. Acco Account unt numbe numberr 2. Balance Balance at at the beginning beginning of the month month 3. Total Total of all items items charged charged by this customer customer this this month 4. Total of all credits applied to this customer's customer's account this month 5. Allowe Allowed d credit credit limi limitt © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

24

Structured Program Development in C: Solutions

Chapter 3

The program should input each of these facts, calculate the new balance ( = beginning balance + charges – credits ), and determine if the new balance exceeds the customer's credit limit. For those customers whose credit limit is exceeded, the program should display the customer's account number, credit limit, new balance and the message “Credit limit exceeded.” exceeded.” Here is a sample input/ output dialog:

Enter account number ( -1 to end): 100 Enter beginning balance: 5394.78 Enter total charges: 1000.00 Enter total credits: 500.00 Enter credit limit: 5500.00 Account: 100 Credit limit: 5500.00 Balance: 5894.78 Credit Limit Exceeded. Enter Enter Enter Enter Enter

account number ( -1 to end ): 200 beginning balance: 1000.00 total charges: 123.45 total credits: 321.00 credit limit: 1500.00

Enter Enter Enter Enter Enter

account number ( -1 to end ): 300 beginning balance: 500.00 total charges: 274.73 total credits: 100.00 credit limit: 800.00

Enter account number ( -1 to end ): -1

ANS: 2)

Top: Determine if Determine if each each of an an arbitrary arbitrary number of department department store custome customers rs has has exceeded exceeded the credit limit on a charge charge account. First refinement: Input the account number, beginning balance, total charges, charges, total total credits, and and credit credit limit for a customer customer,, calcu late the customer’s new balance and determine if the balance exceeds the credit limit. Then process the next customer. Second refinement: Input the first customer’s customer’s account account number. number. While the sentinel value (-1) has not been entered for the account number Input the customer’s beginning balance Input the customer’s total total charges charges Input the customer’s total total credits credits Input the customer’s credit credit limit limit Calculate the customer’s new balance If the balance balance exceeds exceeds the credit credit limit Print the account number Print the credit limit Print the balance Print “Credit Limit Exceeded” Input the next customer’s customer’s account account number. number.

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 25

Chapter 3

3) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

/* Exercise 3.18 Solution */ #include

/* /* /* /* /*

current current current current current

account's account's account's account's account's

number */ starting balance */ total charges */ total credits */ credit limit */

/* get account number */ printf( "\nEnter account number ( -1 to end): " ); scanf( "%d" "%d", , &accountNumber ); /* loop until sentinel value read from user */ while ( accountNumber != -1 ) { printf( "Enter beginning balance: " ); scanf( "%lf" "%lf", , &balance ); printf( "Enter total charges: " ); scanf( "%lf" "%lf", , &charges ); printf( "Enter total credits: " ); scanf( "%lf" "%lf", , &credits ); printf( "Enter credit limit: " ); scanf( "%lf" "%lf", , &limit ); balance += charges - credits; /* calculate balance */ /* if balance is over limit, display account number with credit limit and balance to two digits of precision */ if ( balance > limit ) { printf( "%s%d\n%s%.2f\n%s%.2f\n%s\n", "Account: ", accountNumber, ", accountNumber, "Credit limit: ", ", limit, "Balance: ", balance, "Credit Limit Exceeded." ); ", } /* end if */ /* prompt for next account */ printf( "\nEnter account number ( -1 to end ): " ); scanf( "%d" "%d", , &accountNumber ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

26

Structured Program Development in C: Solutions

Chapter 3

3.19

One large chemical company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5000 worth of chemicals in a week receives $200 plus 9% of $5000, or a total of $650. Develop a program that will input each salesperson's gross sales for last week and will calculate and display that salesperson's earnings. Process one salesperson's figures at a time. Here is a sample input/output dialog: Enter sales in dollars ( -1 to end): 5000.00 Salary is: $650.00 Enter sales in dollars ( -1 to end ): 1234.56 Salary is: $311.11 Enter sales in dollars ( -1 to end ): 1088.89 Salary is: $298.00 Enter sales in dollars ( -1 to end ): -1

ANS: 2)

Top: For an arbitrary number of salespeople, determine each salesperson’s earnings for the last week. First refinement: Input the salesperson’s salesperson’s sales for the week, calculate and print the salesperson’s salesperson’s wages for the the week, week, then process the next salesperson. Second refinement: Input the first salesperson’s salesperson’s sales sales in dollars. dollars. While the sentinel value (-1) has not been entered for the sales Calculate the salesperson’s wages for the week Print the salesperson’s wages for the week Input the next salesperson’s salesperson’s sales sales in dollars dollars

3) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

/* Exercise 3.19 Solution */ #include

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 27

Chapter 3

3.20

The simple interest on a loan is calculated by the formula interest = principal * rate * days / 365 365; ;

The preceding formula assumes that rate is the annual interest rate, and therefore includes the division by 365 (days). Develop a program that will input principal , rate and days for several loans, and will calculate and display the simple interest for each loan, using the preceding formula. Here is a sample input/output dialog:

Enter loan principal ( -1 to end): 1000.00 Enter interest rate: .1 Enter term of the loan in days: 365 The interest charge is $100.00 Enter loan principal ( -1 to end ): 1000.00 Enter interest rate: .08375 Enter term of the loan in days: 224 The interest charge is $51.40 Enter loan principal ( -1 to end ): 10000.00 Enter interest rate: .09 Enter term of the loan in days: 1460 The interest charge is $3600.00 Enter loan principal ( -1 to end ): -1

ANS: 2)

Top: For an arbitrary number of loans determine the simple interest for each loan. First refinement: Input the principal of the loan, loan, the interest interest rate, and the term of the loan, calculate calculate and and print the the simple interest for the loan, loan, and process process the next loan. loan. Second refinement: input the first loan principal in dollars. While the sentinel value (-1) has not been entered for the loan principal Input the interest rate rate Input the term of the loan in days days Calculate the simple interest for the loan Print the simple interest for the loan Input the loan principal principal for the the next loan loan

3) 1 2 3 4 5 6 7 8 9 10 11 12 13

/* Exercise 3.20 Solution */ #include

/* /* /* /*

loan principal */ interest rate */ interest charge */ length of loan in days */

/* get loan principal */ printf( "Enter loan principal ( -1 to end): " ); scanf( "%lf", &principal );

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

28

Structured Program Development in C: Solutions

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

Chapter 3

/* loop until sentinel value is read from user */ while ( principal != -1.0 ) { printf( "Enter interest rate: " ); /* get rate */ scanf( "%lf" "%lf", , &rate ); printf( "Enter term of the loan in days: " ); /* get term */ scanf( "%d" "%d", , &term ); /* calculate interest charge */ interest = principal * rate * term / 365.0 365.0; ; printf( "The interest charge is $%.2f\n\n", interest ); /* get next loan principal */ printf( "Enter loan principal ( -1 to end ): " ); scanf( "%lf" "%lf", , &principal ); } /* end while */ return 0; /* indicate successful termination */ } /* end main */

3.21

Develop a program that will determine the gross pay f or each of several employees. The company pays “straight-time” for the first 40 hours worked by each employee and pays “time-and-a-half” for all hours worked in excess of 40 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee, and should determine and display the employee's gross pay. Here is a sample input/output dialog:

Enter number of hours worked ( -1 to end Enter hourly rate of the worker ( $00.00 Salary is $390.00

): 39 ): 10.00

Enter number of hours worked ( -1 to end Enter hourly rate of the worker ( $00.00 Salary is $400.00

): 40 ): 10.00

Enter number of hours worked ( -1 to end Enter hourly rate of the worker ( $00.00 Salary is $415.00

): 41 ): 10.00

Enter number of hours worked (

): -1

ANS: 2)

-1 to end

Top: For an arbitrary number of employees, determine the gross pay for each employee. First refinement: Input the number of of hours worked worked for the the employee, employee, enter the employee’s employee’s hourly hourly wage, calculate and print the the employee’s gross pay, and process the next employee. Second refinement: Input the first employee’s employee’s number number of hours hours worked. worked. While the sentinel value (-1) has not been entered for the hours worked Input the employee employee’s ’s hourly wage wage Calculate the employee’s gross pay with overtime for hours over 40 Print the employee’s gross pay Input the number of hours worked worked for the next computer computer © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 29

Chapter 3

3) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

/* Exercise 3.21 Solution */ #include

-1 to end

): "

);

/* loop until sentinel value read from user */ while ( hours != -1.0 ) { /* get hourly rate */ printf( "Enter hourly rate of the worker ( scanf( "%lf" "%lf", , &rate );

$00.00

): " );

/* if employee worked less than 40 hours */ if ( hours <= 40 ) { salary = hours * rate; } /* end if */ else { /* compute "time-and-a-half" pay */ salary = 40.0 * rate + ( hours - 40.0 ) * rate * 1.5 1.5; ; } /* end else */ /* display gross pay */ printf( "Salary is $%.2lf\n\n", $%.2lf\n\n", salary /* prompt for next employee's data */ printf( "Enter number of hours worked ( scanf( "%lf" "%lf", , &hours ); } /* end while */

);

-1 to end

): " );

return 0; /* indicate successful termination */ } /* end main */

3.22 Write a program that demonstrates the difference between predecrementing and postdecrementing using the decrement operator --. ANS:

1 2 3 4 5 6 7 8 9 10 11

/* Exercise 3.22 Solution */ #include

12

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

30

Structured Program Development in C: Solutions

13 14 15 16 17 18 19 20

Chapter 3

c = 5; printf( "%d\n", "%d\n", c ); printf( "%d\n" "%d\n", , c-- ); /* postdecrement */ printf( "%d\n\n" "%d\n\n", , c ); return 0; /* indicate successful termination */ } /* end main */

5 4 4 5 5 4

3.23

Write a program that utilizes looping to print the numbers from 1 to 10 side-by-side on the same line with 3 spaces between each number. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

1

/* Exercise 3.23 Solution */ #include

3

4

5

6

7

8

9

10

3.24

The process of finding the largest number (i.e., the maximum of a group of numbers) is used frequently in computer applications. For example, a program that determines the winner of a sales contest would input the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode program and then a program that inputs a series of 10 numbers, and d etermines and prints the largest of the numbers. [ Hint : Your program should use three variables as follows]:

counter: number: largest:

A counter to count to 10 (i.e., to keep track of how many numbers have been input and to determine when all 10 nu mbers have been processed) The current number input to the program The largest number found so far

ANS: Input the first number number directly into the variable variable largest Increment counter to 2

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 31

Chapter 3

While counter is less than or equal to 10 input a new variable into the variable number If number is greater than largest replace largest with number Increment counter Print the value of the largest ( while condition false when counter is 11)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

/* Exercise 3.24 Solution */ #include

Enter the first number: 7 Enter next number: 37 Enter next number: 78 Enter next number: 2 Enter next number: 437 Enter next number: 72 Enter next number: 1 Enter next number: 4 Enter next number: 36 Enter next number: 100 Largest is 437

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

32

Structured Program Development in C: Solutions

3.25

Chapter 3

Write a program that utilizes looping to print the following table of values:

N

10 * N

1 2 3 4 5 6 7 8 9 10

10 20 30 40 50 60 70 80 90 100

100 * N 100 200 300 400 500 600 700 800 900 1000

1000 * N 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000

The tab character, \t, may be used in the printf statement to separate the columns with tabs. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

3.26

/* Exercise 3.25 Solution */ #include

Write a program that utilizes looping to produce the following table of values:

A

A+2

A+4

A+6

3 6 9 12 15

5 8 11 14 17

7 10 13 16 19

9 12 15 18 21

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 33

Chapter 3

ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

/* Exercise 3.26 Solution */ #include

3.27

Using an approach similar to Exercise 3.24, find the two largest values of the 10 numbers. [ Note: You may input each number only once.] ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

/* Exercise 3.27 Solution */ #include

counter; number; largest; secondLargest = 0;

/* /* /* /*

counter for 10 current number largest number second largest

repetitions */ input */ found */ number found */

printf( "Enter the first number: " ); /* get first number */ scanf( "%d" "%d", , &largest ); counter = 2; /* loop 9 more times */ while ( counter <= 10 ) { printf( "Enter next number: " ); /* prompt for next number */ scanf( "%d" "%d", , &number ); /* if current number is greater than largest */ if ( number > largest ) { /* update second largest with previous largest */ secondLargest = largest; /* update largest with current number */ largest = number; } /* end if */ else {

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

34

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

Structured Program Development in C: Solutions

Chapter 3

/* if number is between secondLargest and largest */ if ( number > secondLargest ) { secondLargest secondLargest = number; } /* end if */ } /* end else */ ++counter; } /* end while */ /* display largest two numbers */ printf( "Largest is %d\n", %d\n", largest ); printf( "Second largest is %d\n", %d\n", secondLargest ); return 0; /* indicate successful termination */ } /* end main */

Enter the first number: 100 Enter next number: 102 Enter next number: 83 Enter next number: 3883 Enter next number: 328 Enter next number: 28 Enter next number: 839 Enter next number: 2398 Enter next number: 182 Enter next number: 0 Largest is 3883 Second largest is 2398

3.28 Modify the program in Figure 3.10 to validate its inputs. On any input, if the value entered entered is other than 1 or 2, keep looping until the user enters a correct value. ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

/* Exercise 3.28 Solution */ #include

/* /* /* /*

number of passes */ number of failures */ student counter */ one exam result */

/* process 10 students using counter-controlled loop */ while ( student <= 10 ) { /* prompt user for input and obtain value from user */ printf( "Enter result ( 1=pass, 2=fail ): " ); scanf( "%d" "%d", , &result ); /* loop until valid input */ while ( result != 1 && result != 2 ) { printf( "Invalid result\nEnter result ( 1=pass, 2=fail ): " ); scanf( "%d" "%d", , &result ); } /* end inner while */

23

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 35

Chapter 3

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

/* if result 1, increment passes */ if ( result == 1 ) { ++passes; } /* end if */ else { /* if result is not 1, increment failures */ ++failures; } /* end else */ ++student; } /* end while */ printf( "Passed %d\nFailed %d\n", %d\n", passes, failures ); /* if more than eight students passed, print "raise tuition" */ if ( passes >= 8 ) { printf( "Raise tuition\n" ); } /* end if */ return 0; /* indicate successful termination */ } /* end main */

Enter result ( Enter result ( Enter result ( Invalid result Enter result ( Invalid result Enter result ( Enter result ( Enter result ( Enter result ( Enter result ( Enter result ( Enter result ( Enter result ( Passed 6 Failed 4

3.29

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

1=pass, 2=fail ): 1 1=pass, 2=fail ): 2 1=pass, 2=fail ): 3 1=pass, 2=fail ): 4 1=pass, 1=pass, 1=pass, 1=pass, 1=pass, 1=pass, 1=pass, 1=pass,

2=fail 2=fail 2=fail 2=fail 2=fail 2=fail 2=fail 2=fail

): ): ): ): ): ): ): ):

2 2 2 1 1 1 1 1

What does the following program print? #include

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

36

Structured Program Development in C: Solutions

ANS:

**** ++++++++ **** ++++++++ **** ++++++++ **** ++++++++ **** ++++++++

3.30

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

What does the following program print? #include

ANS:

>>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<< >>>>>>>>>> <<<<<<<<<<

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 3

Structured Program Development in C: Solutions 37

Chapter 3

3.31

(Dangling Else Problem) Determine the output for each of the following when x is 9 and y is 11 and when x is 11 and y is 9. Note that the compiler ignores the indentation in a C program. Also, the compiler always associates an else with the previous if unless told to do otherwise by the placement of braces {}. Because, on first glance, the programmer may not be sure which if an else matches, this is referred to as the “dangling else” pr oblem. We have eliminated the indentation from the followin g code to make the problem more challenging. [ Hint: Hint: Apply indentation conventions you have learned.] a) if ( x < 10 ) if ( y > 10 ) printf( "*****\n" ); else printf( "#####\n" ); printf( "$$$$$\n" ); ANS: x = 9, y = 11

***** $$$$$

x = 11 11, , y = 9

$$$$$

b) if ( x < 10 ) { if ( y > 10 ) printf( "*****\n" ); } else { printf( "#####\n" ); printf( "$$$$$\n" ); } ANS: x = 9, y = 11

*****

x = 11 11, , y = 9

##### $$$$$

3.32

produ ce the output shown. Use proper indentation techniques. (Another Dangling Else Problem) Modify the following code to produce You might not make any changes other than inserting braces. The compiler ignores the indentation in a program. We have eliminated the indentation from the following code to make the problem more challenging. [ Note: It is possible that no modification is necessary.] if ( y == 8 ) if ( x == 5 ) printf( "@@@@@\n" else printf( "#####\n" printf( "$$$$$\n" printf( "&&&&&\n"

); ); ); );

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

38

Structured Program Development in C: Solutions

Chapter 3

a) Assu ssuming x = 5 and y = 8, the following output is produced. @@@@@ $$$$$ &&&&&

ANS: if ( y == 8 ) { if ( x == 5 ) printf( “@@@@@\n” ); else printf( “#####\n” ); printf( “$$$$$\n” ); printf( “&&&&&\n” ); }

b) Ass Assumi uming x = 5 and y = 8, the following output is produced. @@@@@

ANS: if ( y == 8 ) if ( x == 5 ) printf( “@@@@@\n” else { printf( “#####\n” printf( “$$$$$\n” printf( “&&&&&\n” }

); ); ); );

c) Assu ssuming x = 5 and y = 8, the following output is produced. @@@@@ &&&&&

ANS: if ( y == 8 ) if ( x == 5 ) printf( “@@@@@\n” ); else { printf( “#####\n” ); printf( “$$$$$\n” ); } printf( “&&&&&\n” );

d) Ass Assumi uming x = 5 and y = 7, the following output is produced. [ Note: The last three printf statements are all part of a compound statement. ##### $$$$$ &&&&&

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 39

Chapter 3

ANS: if ( y == 8 ) { if ( x == 5 ) printf( “@@@@@\n” ); } else { printf( “#####\n” ); printf( “$$$$$\n” ); printf( “&&&&&\n” ); } 3.33

Write a program that reads in the side of a square and then prints that square out of asterisks. Your program should work for squares of all side sizes between 1 and 20. For example, if your program reads a size of 4, it should print **** **** **** ****

ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

/* Exercise 3.33 Solution */ #include

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

40

Structured Program Development in C: Solutions

3.34

Chapter 3

Modify the program you wrote in Exercise 3.33 so that it prints a hollow square. For example, if your prog ram reads a size of 5, it should print ***** * * * * * * *****

ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

/* Exercise 3.34 Solution */ #include

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 41

Chapter 3

3.35

A palindrome is a number o r a text phrase that reads the same backwards as forwards. For example, each of the following five-digit integers are palindromes: 12321, 55555, 45554 and 11611. Write a program that reads in a five-digit integer and determines whether or not it is a palindrome. [ Hint : Use the division and r emainder operators to separate the number into its individual digits.] ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

/* Exercise 3.35 Solution */ #include

/* /* /* /* /* /* /*

input number */ first temporary integer */ second temporary integer */ first digit of input */ second digit of input */ fourth digit of input */ fifth digit of input */

printf( "Enter a five-digit number: " ); /* get number */ scanf( "%d" "%d", , &number ); temp1 = number; /* determine first digit by integer division by 10000 */ firstDigit = temp1 / 10000 10000; ; temp2 = temp1 % 10000 10000; ; /* determine second digit by integer division by 1000 */ secondDigit secondDigit = temp2 / 1000 1000; ; temp1 = temp2 % 1000 1000; ; temp2 = temp1 % 100 100; ; /* determine fourth digit by integer division by 10 */ fourthDigit fourthDigit = temp2 / 10 10; ; temp1 = temp2 % 10 10; ; fifthDigit = temp1; /* if first and fifth digits are equal */ if ( firstDigit == fifthDigit ) { /* if second and fourth digits are equal */ if ( secondDigit == fourthDigit ) { /* number is a palindrome */ printf( "%d is a palindrome\n" palindrome\n", , number ); } /* end if */ else { /* number is not a palindrome */ printf( "%d is not a palindrome\n", palindrome\n", number ); } /* end else */ } /* end if */ else { /* number is not a palindrome */ printf( "%d is not a palindrome\n", palindrome\n", number ); } /* end else */ return 0; /* indicate successful termination */ } /* end main */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

42

Structured Program Development in C: Solutions

Chapter 3

Enter a five-digit number: 18181 18181 is a palindrome

Enter a five-digit number: 16738 16738 is not a palindrome

3.36

Input an integer containing only 0s and 1s (i.e., a “binary” integer) and print its decimal equivalent. [ Hint : Use the remainder and division operators to pick off the “binary” number’s digits one at a time from right to left. Just as in the decimal number system in which the rightmost digit has a positional value of 1, and the next digit left has a positional value of 10 , then 100, then 1000, etc., in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, etc. Thus the decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8 or 13.] ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

/* Exercise 3.36 Solution */ #include

/* /* /* /* /*

current value of binary number */ input binary number */ current value of decimal number */ value of highest bit */ factor of 10 to pick off digits */

/* prompt for binary input */ printf( "Enter a binary number ( 5 digits maximum ): " ); scanf( "%d" "%d", , &binary ); number = binary; /* save in number for final display */ /* loop 5 times using powers of 2 */ while ( highBit >= 1 ) { /* update decimal value with decimal value corresponding to current highest binary bit */ decimal += binary / factor * highBit; /* reduce high bit by factor of 2, i.e., move one bit to the right */ highBit /= 2; /* reduce binary number to eliminate current highest bit */ binary %= factor; /* reduce factor by power of 10, i.e., move one bit to the right */ factor /= 10 10; ; } /* end while */ /* display decimal value */ printf( "The decimal equivalent of %d is %d\n", %d\n", number, decimal ); return 0; /* indicate successful termination */ } /* end main */

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 43

Chapter 3

Enter a binary number ( 5 digits maximum ): 10111 The decimal equivalent of 10111 is 23

Enter a binary number ( 5 digits maximum ): 1101 The decimal equivalent of 1101 is 13

3.37 How can you determine how fast your own computer really operates? Write a program with a while loop that counts from 1 to 300,000,000 by 1s. Every time the count reaches a multiple of 100,000,000 print that number on the screen. Use your watch to time how long each million repetitions of the loop takes. ANS:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

/* Exercise 3.37 Solution */ #include

Multiple is 1 Multiple is 2 Multiple is 3

3.38

Write a program that prints 100 asterisks, one at a time. After every tenth asterisk, your program should print a newline character. (Hint: Count from 1 to 100. Use the remainder operator to recognize each time the counter reaches a multiple of 10.) ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14

/* Exercise 3.38 Solution */ #include

return 0; /* indicate successful termination */ © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

44

Structured Program Development in C: Solutions

15 16

} /* end main */

********** ********** ********** ********** ********** ********** ********** ********** ********** **********

3.39

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

Write a program that reads an integer and determines and prints how m any digits in the integer are 7s. ANS: /* Exercise 3.39 Solution */ #include

/* /* /* /* /*

user input */ copy of number */ set factor to pick off digits */ individual digit of number */ sevens counter */

printf( "Enter a 5-digit number: " ); /* get number from user */ scanf( "%d" "%d", , &number ); numCopy = number; /* loop through each of the 5 digits */ while ( factor >= 1 ) { digit = numCopy / factor; /* pick off next digit */ if ( digit == 7 ) { /* if digit equals 7, increment sevens */ ++sevens; } /* end if */ numCopy %= factor; factor /= 10 10; ; } /* end while */ /* output number of sevens */ printf( "The number %ld has %d seven(s) in it\n", it\n", number, sevens ); return 0; /* indicate successful termination */ } /* end main */

Enter a 5-digit number: 17737 The number 17737 has 3 seven(s) in it

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 3

Structured Program Development in C: Solutions 45

Chapter 3

Enter a 5-digit number: 11727 The number 11727 has 2 seven(s) in it

3.40

Write a program that displays the following checkerboard pattern * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Your program must use only three output statements, one of each of the following forms: printf( "* " ); printf( " " ); printf( "\n" );

ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

/* Exercise 3.40 Solution */ #include

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

46

Structured Program Development in C: Solutions

Chapter 3

3.41

Write a program that keeps printing the multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. Your loop should not terminate (i.e., you should create an infinite loop). What happens when you run this program? ANS: Program execution terminates when largest integer is exceeded (i.e., the loop continuation test fails when the maximum value for an integer is exceeded. On a 4-byte system, the largest integer integer value is 2147483647 and anything above that is represented by a negative number, which fails the loop continuation test). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

/* Exercise 3.41 Solution */ #include

2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648

3.42

Write a program that reads the radius of a circle (as a float value) and computes and prints the diameter, the circumference and the area. Use the value 3.14159 for π. © Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 47

Chapter 3

ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

/* Exercise 3.42 Solution */ #include

Enter the radius: 4.7 The diameter is 9.40 The circumference is 29.53 The area is 69.40

3.43 What is wrong with the following statement? Rewrite the statement to accomplish what the programmer was probably trying to do.

printf( "%d" "%d", , ++( x + y ) );

ANS: printf( “%d” “%d”, , 1 + x + y ); 3.44

Write a program that reads three n onzero float values and determines and prints if they could represent the sides of a tri-

angle. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

/* Exercise 3.44 Solution */ #include

48

Structured Program Development in C: Solutions

18 19 20 21 22 23 24 25

Chapter 3

else { printf( "The three numbers probably"); probably"); printf( " are not the sides of a triangle\n" ); } /* end if */ return 0; /* indicate successful termination */ } /* end main */

Enter three doubleing point numbers: 5.7 3.6 2.2 The three numbers probably are not the sides of a triangle

Enter three doubleing point numbers: 3.0 4.0 5.0 The three numbers could be sides of a triangle

3.45

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Write a program that reads three nonzero integers and determines and prints if they could be the sides of a right triangle. ANS: /* Exercise 3.45 Solution */ #include

Enter three integers: 3 4 5 The three integers are the sides of a right triangle

Enter three integers: 9 4 1 The three integers are not the sides of a right triangle

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 49

Chapter 3

3.46

A company wants to transmit data over the telephone, but they are concerned that their phones may be tapped. All of their data is transmitted as four-digit integers. They have asked you to write a program that will encrypt their data so that it may be transmitted more securely. Your program should read a four-digit integer and encrypt it as follows: Replace each digit by the remainder after (the sum of that digit plus 7) is divided by 10. Then, swap the first digit with the third, and swap the second digit with the fourth. Then print the encrypted integer. Write a separate program that inputs an encrypted four-digit integer and decrypts it to form the original number. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

/* Exercise 3.46 Part A solution */ #include

first and third */ first; third * 1000 1000; ; /* multiply by 1000 for 1st digit component */ temp1 * 10 10; ; /* multiply by 10 for 3rd digit component */

/* swap second and fourth */ temp1 = second; second = fourth * 100 100; ; /* multiply by 100 for 2nd digit component */ fourth = temp1 * 1; /* add components to obtain encrypted number */ encryptedNumber = first + second + third + fourth; /* display encrypted number */ printf( "Encrypted number is %d\n", %d\n", encryptedNumber ); return 0; /* indicate successful termination */ } /* end main */

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

50

Structured Program Development in C: Solutions

Enter a four digit number to be encrypted: 5678 Encrypted number is 4523

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

/* Exercise 3.46 Part B Solution */ #include

Enter a four digit encrypted number: 4523 Decrypted number is 5678

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 3

Structured Program Development in C: Solutions 51

Chapter 3

1.1

The factorial of a nonnegative integer n is written n! (pronounced “n factorial”) and is defined as follows: values of n greater than or equal to 1) n! = n · (n - 1) · ( n - 2) · … · 1 (for values

and n! = 1 (for n = 0). For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. a) Write a program that reads a nonnegative integer integer and computes computes and prints its factorial. ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

/* Exercise 3.47 Part A Solution */ #include

Enter a positive integer: 5 5! is 120

Enter a positive integer: 9 9! is 362880

Enter a positive integer: -8 Enter a positive integer: 0 0! is 1

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

52

Structured Program Development in C: Solutions

Chapter 3

b) Write a program that estimates the value of the mathematical mathematical constant e by using the formula: e

=

1

1

1

1

+ ----- + ----- + ----- + … 1! 2! 3!

ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

/* Exercise 3.47 Part B Solution */ #include

/* /* /* /*

loop counter for accuracy */ current n factorial */ degree of accuracy */ current estimated value of e */

/* loop until degree of accuracy */ while( while ( n <= accuracy ) { if ( n == 0 ) { fact *= 1; } /* end if */ else { fact *= n; } /* end else */ e += 1.0 / fact; ++n; } /* end while */ printf( "e is %f\n", %f\n", e ); /* display estimated value */ return 0; /* indicate successful termination */ } /* end main */

e is 2.718282

c) Write a program program that that compute computess the value value of e x by using the formula 2 x

e

=

1

x

x

3

x

+ ----- + ----- + ----- + … 1! 2! 3!

ANS: 1 2 3 4 5 6 7 8 9 10 11 12 13 14

/* Exercise 3.47 Part C Solution */ #include

/* /* /* /* /* /* /* /*

counter */ degree of accuracy */ exponent */ counter */ copy of n */ e raised to the x power */ x raised to the n power */ n factorial */

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Structured Program Development in C: Solutions 53

Chapter 3

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

/* loop while less than degree of accuracy */ while( while ( n <= accuracy ) { count = n; /* update n! */ if ( n == 0 ) { fact *= 1.0 1.0; ; } /* end if */ else { fact *= n; } /* end else */ while ( times < count ) { /* calculate x raised to the n power */ if ( times == 0 ) { exp = 1.0 1.0; ; exp *= x; } /* end if */ else { exp *= x; } /* end else */ ++times; } /* end while */ e += exp / fact; /* update e raised to the x power */ ++n; } /* end while */ /* display result */ printf( "e raised to the %d power is %f\n" %f\n", , x, e ); return 0; /* indicate successful termination */ } /* end main */

e raised to the 3 power is 20.085534

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

54

Structured Program Development in C: Solutions

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 3

Our partners will collect data and use cookies for ad personalization and measurement. Learn how we and our ad partner Google, collect and use data. Agree & close