Top Banner
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 3 Structured Program Development in C: Solutions 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", y ); ++y; }
36

Chapter 3 Solutions

Nov 08, 2014

Download

Documents

Kilo batates
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 3 Solutions

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

3Structured Program

Development in C: Solutions

SOLUTIONS3.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", y ); ++y;}

Page 2: Chapter 3 Solutions

20 Structured Program Development in C: Solutions Chapter 3

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

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

3.12 Fill in the blanks in each of the following:a) The solution to any problem involves performing a series of actions in a specific .ANS: order.b) A synonym for procedure is .ANS: algorithmc) A variable that accumulates the sum of several 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 value used to indicate “end of data entry” is called a , a , a or a

value.ANS: sentinel value, dummy value, signal value, flag value.f) A is a graphical representation of an algorithm.ANS: flowchart.g) In a flowchart, the order in which the steps should be performed is indicated by symbols.ANS: arrow (flowline).h) The termination symbol indicates the and of every algorithm.ANS: beginning, end.i) Rectangle symbols correspond to calculations that are normally performed by statements and input/output

operations that are normally performed by calls to the and standard library functions.ANS: assignment, printf, scanf.j) The item written inside a decision symbol is called a .ANS: condition.

3.13 What does the following program print?

1 #include <stdio.h>23 int main()4 {5 int x = 1, total = 0, y;67 while ( x <= 10 ) {8 y = x * x;9 printf( "%d\n", y );

10 total += y;11 ++x;12 }1314 printf("Total is %d\n", total);1516 return 0;17 }

Page 3: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 21

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

3.14 Write a single pseudocode statement that indicates each of the following:a) Display the message "Enter two numbers".ANS: print “enter two numbers”b) Assign the sum of variables x, y, and z to variable p.ANS: p = x + y + zc) The following condition is to be tested in an if…else selection 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 values for variables 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 numberInput the second numberAdd the two numbersOutput the sum

b) Obtain two numbers from the keyboard, and determine and display which (if either) is the larger of the two numbers.ANS:

Input the first number from the keyboardInput the second number from the keyboardIf the first number is greater than the second number print itElse if the second number is greater than the first number print itElse print a message stating that the numbers are equal

c) Obtain a series of positive numbers from the keyboard, and determine and display the sum of the numbers. Assume thatthe user types the sentinel value -1 to indicate “end of data entry.”

ANS: Input a value from the keyboardWhile the input value is not equal to -1 add the number to the running total input the next numberPrint 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 a working C pro-

gram.

149162536496481100Total is 385

Page 4: Chapter 3 Solutions

22 Structured Program Development in C: Solutions Chapter 3

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

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 data value.ANS: True.c) Flowlines indicate the actions to be performed.ANS: False. Flowlines indicate the order in which steps are performed.d) Conditions written inside decision symbols always contain arithmetic operators (i.e., +, -, *, /, and %).ANS: False. They normally contain conditional operators.e) In top-down, stepwise refinement, each refinement is a complete representation of the algorithm.ANS: True.

For Exercises 3.17 to 3.21, perform each of these steps:

1. Read the problem statement.

2. Formulate the algorithm using pseudocode and top-down, stepwise refinement.

3. Write a C program.

4. Test, debug, and execute the C program.

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

ANS: 2) Top:

Determine the average miles/gallon for each tank of gas, and the overall miles/gallon for an arbitrary number oftanks of gas

First refinement:Initialize variables

Input the gallons used and the miles driven, and calculate and print the miles/gallon for each tank of gas. Keeptrack of the total miles and the total gallons.

Calculate and print the overall average miles/gallon.

Second refinement:Initialize totalGallons to zero.Initialize totalMiles to zero.

Input the gallons used for the first tank.

Enter the gallons used (-1 to end): 12.8Enter the miles driven: 287The miles / gallon for this tank was 22.421875

Enter the gallons used (-1 to end): 10.3Enter the miles driven: 200The miles / gallon for this tank was 19.417475

Enter the gallons used (-1 to end): 5Enter the miles driven: 120The miles / gallon for this tank was 24.000000

Enter the gallons used (-1 to end): -1

The overall average miles/gallon was 21.601423

Page 5: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 23

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

While the sentinel value (-1) has not been entered for the gallonsAdd gallons to the running total in totalGallonsInput the miles driven for the current tankAdd miles to the running total in totalMilesCalculate and print the miles/gallonInput the gallons used for the next tank

Set totalAverage to totalMiles divided by totalGallons.print the average miles/gallon

3)

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. Account number

2. Balance at the beginning of the month

3. Total of all items charged by this customer this month

4. Total of all credits applied to this customer's account this month

5. Allowed credit limit

1 /* Exercise 3.17 Solution */2 #include <stdio.h>34 int main()5 { 6 double gallons; /* gallons used for current tank*/7 double miles; /* miles driven for current tank*/8 double totalGallons = 0.0; /* total gallons used */9 double totalMiles = 0.0; /* total miles driven */

10 double totalAverage; /* average miles/gallon */1112 /* get gallons used for first tank */13 printf( "Enter the gallons used ( -1 to end): " ); 14 scanf( "%lf", &gallons ); 1516 /* loop until sentinel value read from user */17 while ( gallons != -1.0 ) { 18 totalGallons += gallons; /* add current tank gallons to total */1920 printf( "Enter the miles driven: " ); /* get miles driven */21 scanf( "%lf", &miles );22 totalMiles += miles; /* add current tank miles to total */2324 /* display miles per gallon for current tank */25 printf( "The Miles / Gallon for this tank was %f\n\n", 26 miles / gallons );2728 /* get next tank's gallons */29 printf( "Enter the gallons used ( -1 to end ): " );30 scanf( "%lf", &gallons );31 } /* end while */3233 /* calculate average miles per gallon over all tanks */34 totalAverage = totalMiles / totalGallons; 35 printf( "\nThe overall average Miles/Gallon was %f\n", totalAverage );3637 return 0; /* indicate successful termination */3839 } /* end main */

Page 6: Chapter 3 Solutions

24 Structured Program Development in C: Solutions Chapter 3

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

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

ANS: 2) Top:

Determine if each of an arbitrary number of department store customers has exceeded the credit limit on a chargeaccount.

First refinement:Input the account number, beginning balance, total charges, total credits, and credit limit for a customer, calculate the customer’s new balance and determine if the balance exceeds the credit limit. Then process the next cus-tomer.

Second refinement:Input the first customer’s account number.

While the sentinel value (-1) has not been entered for the account numberInput the customer’s beginning balanceInput the customer’s total chargesInput the customer’s total creditsInput the customer’s credit limitCalculate the customer’s new balance

If the balance exceeds the credit limitPrint the account numberPrint the credit limitPrint the balancePrint “Credit Limit Exceeded”Input the next customer’s account number.

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

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

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

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

Page 7: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 25

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

3)

1 /* Exercise 3.18 Solution */2 #include <stdio.h>34 int main()5 { 6 int accountNumber; /* current account's number */7 double balance; /* current account's starting balance */8 double charges; /* current account's total charges */9 double credits; /* current account's total credits */

10 double limit; /* current account's credit limit */11 12 /* get account number */13 printf( "\nEnter account number ( -1 to end): " );14 scanf( "%d", &accountNumber );1516 /* loop until sentinel value read from user */17 while ( accountNumber != -1 ) { 18 printf( "Enter beginning balance: " );19 scanf( "%lf", &balance );2021 printf( "Enter total charges: " );22 scanf( "%lf", &charges );2324 printf( "Enter total credits: " );25 scanf( "%lf", &credits );2627 printf( "Enter credit limit: " );28 scanf( "%lf", &limit );2930 balance += charges - credits; /* calculate balance */3132 /* if balance is over limit, display account number33 with credit limit and balance to two digits of precision */34 if ( balance > limit ) {35 printf( "%s%d\n%s%.2f\n%s%.2f\n%s\n",36 "Account: ", accountNumber, "Credit limit: ", limit,37 "Balance: ", balance, "Credit Limit Exceeded." );38 } /* end if */3940 /* prompt for next account */41 printf( "\nEnter account number ( -1 to end ): " );42 scanf( "%d", &accountNumber );43 } /* end while */4445 return 0; /* indicate successful termination */4647 } /* end main */

Page 8: Chapter 3 Solutions

26 Structured Program Development in C: Solutions Chapter 3

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

3.19 One large chemical company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% oftheir 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 displaythat salesperson's earnings. Process one salesperson's figures at a time. Here is a sample input/output dialog:

ANS: 2) Top:

For an arbitrary number of salespeople, determine each salesperson’s earnings for the last week.

First refinement:Input the salesperson’s sales for the week, calculate and print the salesperson’s wages for the week, then processthe next salesperson.

Second refinement:Input the first salesperson’s sales in dollars.While the sentinel value (-1) has not been entered for the sales

Calculate the salesperson’s wages for the weekPrint the salesperson’s wages for the weekInput the next salesperson’s sales in dollars

3)

Enter sales in dollars ( -1 to end): 5000.00Salary is: $650.00

Enter sales in dollars ( -1 to end ): 1234.56Salary is: $311.11

Enter sales in dollars ( -1 to end ): 1088.89Salary is: $298.00

Enter sales in dollars ( -1 to end ): -1

1 /* Exercise 3.19 Solution */2 #include <stdio.h>34 int main()5 { 6 double sales; /* gross weekly sales */7 double wage; /* commissioned earnings */8 9 /* get first sales */

10 printf( "Enter sales in dollars ( -1 to end): " );11 scanf( "%lf", &sales );1213 /* loop until sentinel value read from user */14 while ( sales != -1.0 ) { 15 wage = 200.0 + 0.09 * sales; /* calculate wage */1617 /* display salary */18 printf( "Salary is: $%.2f\n\n", wage );1920 /* prompt for next sales */21 printf( "Enter sales in dollars ( -1 to end ): " );22 scanf( "%lf", &sales );23 } /* end while */2425 return 0; /* indicate successful termination */2627 } /* end main */

Page 9: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 27

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

3.20 The simple interest on a loan is calculated by the formula

interest = principal * rate * days / 365;

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

ANS: 2) Top:

For an arbitrary number of loans determine the simple interest for each loan.

First refinement:Input the principal of the loan, the interest rate, and the term of the loan, calculate and print the simple interestfor the loan, and process the next 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 rateInput the term of the loan in daysCalculate the simple interest for the loanPrint the simple interest for the loanInput the loan principal for the next loan

3)

Enter loan principal ( -1 to end): 1000.00Enter interest rate: .1Enter term of the loan in days: 365The interest charge is $100.00

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

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

Enter loan principal ( -1 to end ): -1

1 /* Exercise 3.20 Solution */2 #include <stdio.h>34 int main()5 { 6 double principal; /* loan principal */7 double rate; /* interest rate */8 double interest; /* interest charge */9 int term; /* length of loan in days */

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

Page 10: Chapter 3 Solutions

28 Structured Program Development in C: Solutions Chapter 3

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

3.21 Develop a program that will determine the gross pay for each of several employees. The company pays “straight-time” forthe first 40 hours worked by each employee and pays “time-and-a-half” for all hours worked in excess of 40 hours. You are givena 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. Hereis a sample input/output dialog:

ANS: 2) Top:

For an arbitrary number of employees, determine the gross pay for each employee.

First refinement:Input the number of hours worked for the employee, enter the employee’s hourly wage, calculate and print theemployee’s gross pay, and process the next employee.

Second refinement:Input the first employee’s number of hours worked.While the sentinel value (-1) has not been entered for the hours worked

Input the employee’s hourly wageCalculate the employee’s gross pay with overtime for hours over 40Print the employee’s gross payInput the number of hours worked for the next computer

1415 /* loop until sentinel value is read from user */16 while ( principal != -1.0 ) { 17 printf( "Enter interest rate: " ); /* get rate */18 scanf( "%lf", &rate );1920 printf( "Enter term of the loan in days: " ); /* get term */21 scanf( "%d", &term );22 23 /* calculate interest charge */24 interest = principal * rate * term / 365.0;25 printf( "The interest charge is $%.2f\n\n", interest );2627 /* get next loan principal */28 printf( "Enter loan principal ( -1 to end ): " );29 scanf( "%lf", &principal );30 } /* end while */3132 return 0; /* indicate successful termination */3334 } /* end main */

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

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

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

Enter number of hours worked ( -1 to end ): -1

Page 11: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 29

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

3)

3.22 Write a program that demonstrates the difference between predecrementing and postdecrementing using the decrement op-erator --.

ANS:

1 /* Exercise 3.21 Solution */2 #include <stdio.h>34 int main( void )5 { 6 double hours; /* total hours worked */7 double rate; /* hourly pay rate */8 double salary; /* gross pay */9

10 /* get first employee's hours worked */11 printf( "Enter number of hours worked ( -1 to end ): " );12 scanf( "%lf", &hours );1314 /* loop until sentinel value read from user */15 while ( hours != -1.0 ) { 1617 /* get hourly rate */18 printf( "Enter hourly rate of the worker ( $00.00 ): " );19 scanf( "%lf", &rate );20 21 /* if employee worked less than 40 hours */22 if ( hours <= 40 ) {23 salary = hours * rate;24 } /* end if */25 else { /* compute "time-and-a-half" pay */26 salary = 40.0 * rate + ( hours - 40.0 ) * rate * 1.5;27 } /* end else */2829 /* display gross pay */30 printf( "Salary is $%.2lf\n\n", salary );3132 /* prompt for next employee's data */33 printf( "Enter number of hours worked ( -1 to end ): " );34 scanf( "%lf", &hours );35 } /* end while */3637 return 0; /* indicate successful termination */3839 } /* end main */

1 /* Exercise 3.22 Solution */2 #include <stdio.h>34 int main()5 { 6 int c; /* define c to use decrement operator */7 8 c = 5;9 printf( "%d\n", c );

10 printf( "%d\n", --c ); /* predecrement */11 printf( "%d\n\n", c );12

Page 12: Chapter 3 Solutions

30 Structured Program Development in C: Solutions Chapter 3

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

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 betweeneach number.

ANS:

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

counter: A counter to count to 10 (i.e., to keep track of how many numbers havebeen input and to determine when all 10 numbers have been processed)

number: The current number input to the programlargest: The largest number found so far

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

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

544

554

1 /* Exercise 3.23 Solution */2 #include <stdio.h>34 int main()5 { 6 int i = 0; /* initialize i */78 /* loop while i is less than 11 */9 while ( ++i < 11 ) {

10 printf( "%d ", i );11 } /* end while */1213 return 0; /* indicate successful termination */1415 } /* end main */

1 2 3 4 5 6 7 8 9 10

Page 13: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 31

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

While counter is less than or equal to 10input a new variable into the variable numberIf number is greater than largest

replace largest with numberIncrement counter

Print the value of the largest (while condition false when counter is 11)

1 /* Exercise 3.24 Solution */2 #include <stdio.h>34 int main()5 { 6 int counter; /* counter for 10 repetitions */7 int number; /* current number input */8 int largest; /* largest number found so far */9

10 /* get first number */11 printf( "Enter the first number: " );12 scanf( "%d", &largest );13 counter = 2;14 15 /* loop 9 more times */16 while ( counter <= 10 ) { 17 printf( "Enter next number: " ); /* get next number */18 scanf( "%d", &number );19 20 /* if current number input is greater than largest number,21 update largest */22 if ( number > largest ) { 23 largest = number;24 } /* end if */2526 counter++;27 } /* end while */28 29 printf( "Largest is %d\n", largest ); /* display largest number */3031 return 0; /* indicate successful termination */3233 } /* end main */

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

Page 14: Chapter 3 Solutions

32 Structured Program Development in C: Solutions Chapter 3

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

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

The tab character, \t, may be used in the printf statement to separate the columns with tabs.ANS:

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

N 10 * N 100 * N 1000 * N

1 10 100 1000 2 20 200 2000 3 30 300 3000 4 40 400 4000 5 50 500 5000 6 60 600 6000 7 70 700 7000 8 80 800 8000 9 90 900 9000 10 100 1000 10000

1 /* Exercise 3.25 Solution */2 #include <stdio.h>34 int main()5 { 6 int n = 0; /* counter */7 8 /* display table headers */9 printf( "\tN\t\t10 * N\t\t100 * N\t\t1000 * N\n\n" );

1011 /* loop 10 times */12 while ( ++n <= 10 ) {1314 /* calculate and display table values */15 printf( "\t%-2d\t\t%-5d\t\t%-5d\t\t%-6d\n",16 n, 10 * n, 100 * n, 1000 * n );17 } /* end while */1819 return 0; /* indicate successful termination */2021 } /* end main */

A A+2 A+4 A+6

3 5 7 96 8 10 129 11 13 1512 14 16 1815 17 19 21

Page 15: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 33

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

ANS:

3.27 Using an approach similar to Exercise 3.24, find the two largest values of the 10 numbers. [Note: You may input each num-ber only once.]

ANS:

1 /* Exercise 3.26 Solution */2 #include <stdio.h>34 int main()5 { 6 int a = 3; /* counter */78 /* display table headers */9 printf( "A\tA+2\tA+4\tA+6\n\n" );

1011 /* loop 5 times */12 while ( a <= 15 ) { 1314 /* calculate and display table values */15 printf( "%d\t%d\t%d\t%d\n", a, a + 2, a + 4, a + 6 );16 a += 3;17 } /* end while */1819 return 0; /* indicate successful termination */2021 } /* end main */

1 /* Exercise 3.27 Solution */2 #include <stdio.h>34 int main()56 { 7 int counter; /* counter for 10 repetitions */8 int number; /* current number input */9 int largest; /* largest number found */

10 int secondLargest = 0; /* second largest number found */1112 printf( "Enter the first number: " ); /* get first number */13 scanf( "%d", &largest );14 counter = 2;1516 /* loop 9 more times */17 while ( counter <= 10 ) { 18 printf( "Enter next number: " ); /* prompt for next number */19 scanf( "%d", &number );2021 /* if current number is greater than largest */22 if ( number > largest ) { 2324 /* update second largest with previous largest */25 secondLargest = largest;2627 /* update largest with current number */28 largest = number;29 } /* end if */30 else { 31

Page 16: Chapter 3 Solutions

34 Structured Program Development in C: Solutions Chapter 3

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

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

ANS:

32 /* if number is between secondLargest and largest */33 if ( number > secondLargest ) {34 secondLargest = number;35 } /* end if */3637 } /* end else */3839 ++counter;40 } /* end while */4142 /* display largest two numbers */43 printf( "Largest is %d\n", largest );44 printf( "Second largest is %d\n", secondLargest );4546 return 0; /* indicate successful termination */4748 } /* end main */

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

1 /* Exercise 3.28 Solution */2 #include <stdio.h>34 int main()5 { 6 int passes = 0; /* number of passes */7 int failures = 0; /* number of failures */8 int student = 1; /* student counter */9 int result; /* one exam result */

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

Page 17: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 35

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

3.29 What does the following program print?

24 /* if result 1, increment passes */25 if ( result == 1 ) {26 ++passes;27 } /* end if */28 else { /* if result is not 1, increment failures */29 ++failures;30 } /* end else */3132 ++student;33 } /* end while */34 35 printf( "Passed %d\nFailed %d\n", passes, failures );36 37 /* if more than eight students passed, print "raise tuition" */38 if ( passes >= 8 ) {39 printf( "Raise tuition\n" );40 } /* end if */4142 return 0; /* indicate successful termination */4344 } /* end main */

Enter result ( 1=pass, 2=fail ): 1Enter result ( 1=pass, 2=fail ): 2Enter result ( 1=pass, 2=fail ): 3Invalid resultEnter result ( 1=pass, 2=fail ): 4Invalid resultEnter result ( 1=pass, 2=fail ): 2Enter result ( 1=pass, 2=fail ): 2Enter result ( 1=pass, 2=fail ): 2Enter result ( 1=pass, 2=fail ): 1Enter result ( 1=pass, 2=fail ): 1Enter result ( 1=pass, 2=fail ): 1Enter result ( 1=pass, 2=fail ): 1Enter result ( 1=pass, 2=fail ): 1Passed 6Failed 4

1 #include <stdio.h>23 /* function main begins program execution */4 int main()5 {6 int count = 1; /* initialize count */78 while ( count <= 10 ) { /* loop 10 times */9

10 /* output line of text */11 printf( "%s\n", count % 2 ? "****" : "++++++++" );12 count++; /* increment count */13 } /* end while */1415 return 0; /* indicate program ended successfully */1617 } /* end function main */

Page 18: Chapter 3 Solutions

36 Structured Program Development in C: Solutions Chapter 3

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

ANS:

3.30 What does the following program print?

ANS:

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

1 #include <stdio.h>23 /* function main begins program execution */4 int main()5 {6 int row = 10; /* initialize row */7 int column; /* define column */89 while ( row >= 1 ) { /* loop until row < 1 */

10 column = 1; /* set column to 1 as iteration begins */1112 while ( column <= 10 ) { /* loop 10 times */13 printf( "%s", row % 2 ? "<": ">" ); /* output */14 column++; /* increment column */15 } /* end inner while */1617 row--; /* decrement row */18 printf( "\n" ); /* begin new output line */19 } /* end outer while */2021 return 0; /* indicate program ended successfully */2223 } /* end function main */

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

Page 19: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 37

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

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 unlesstold to do otherwise by the placement of braces {}. Because, on first glance, the programmer may not be sure which if an else match-es, this is referred to as the “dangling else” problem. We have eliminated the indentation from the following code to make the problemmore challenging. [Hint: Apply indentation conventions you have learned.]

a) if ( x < 10 )if ( y > 10 )printf( "*****\n" ); elseprintf( "#####\n" );printf( "$$$$$\n" );

ANS: x = 9, y = 11

x = 11, y = 9

b) if ( x < 10 ) {if ( y > 10 )printf( "*****\n" ); }else {printf( "#####\n" );printf( "$$$$$\n" );}

ANS: x = 9, y = 11

x = 11, y = 9

3.32 (Another Dangling Else Problem) Modify the following code to produce the output shown. Use proper indentation techniques.You might not make any changes other than inserting braces. The compiler ignores the indentation in a program. We have eliminatedthe 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" );elseprintf( "#####\n" );printf( "$$$$$\n" );printf( "&&&&&\n" );

*****$$$$$

$$$$$

*****

#####$$$$$

Page 20: Chapter 3 Solutions

38 Structured Program Development in C: Solutions Chapter 3

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

a) Assuming 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) Assuming 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) Assuming 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) Assuming x = 5 and y = 7, the following output is produced. [Note: The last three printf statements are all part of acompound statement.

@@@@@$$$$$&&&&&

@@@@@

@@@@@&&&&&

#####$$$$$&&&&&

Page 21: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 39

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

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 workfor squares of all side sizes between 1 and 20. For example, if your program reads a size of 4, it should print

ANS:

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

1 /* Exercise 3.33 Solution */2 #include<stdio.h>34 int main()5 { 6 int side; /* side counter */7 int temp; /* temporary integer */8 int asterisk; /* asterisk counter */9

10 printf( "Enter the square side: " ); /* get size of square */11 scanf( "%d", &side );1213 temp = side;1415 /* loop through rows of square */16 while ( side-- > 0 ) { 17 asterisk = temp;1819 /* loop through columns of square */20 while ( asterisk-- > 0 ) {21 printf( "*" );22 } /* end inner while */2324 putchar( '\n' );25 } /* end outer while */26 27 return 0; /* indicate successful termination */2829 } /* end main */

Page 22: Chapter 3 Solutions

40 Structured Program Development in C: Solutions Chapter 3

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

3.34 Modify the program you wrote in Exercise 3.33 so that it prints a hollow square. For example, if your program reads a sizeof 5, it should print

ANS:

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

1 /* Exercise 3.34 Solution */2 #include<stdio.h>34 int main()5 { 6 int side; /* side counter */7 int rowPosition; /* row counter */8 int size; /* length of side */9

10 printf( "Enter the square side: " ); /* prompt for side length */11 scanf( "%d", &side );1213 size = side; /* set size counter to length of side */1415 /* loop side number of times */16 while ( side > 0 ) { 17 rowPosition = size; /* set row counter to length of size */1819 /* loop rowPosition number of times */20 while ( rowPosition > 0 ) { 2122 /* if side or row counter is 1 or size print an '*' */23 if ( size == side ) {24 printf( "*" );25 } /* end if */26 else if ( side == 1 ) {27 printf( "*" );28 } /* end else if */29 else if ( rowPosition == 1 ) {30 printf( "*" );31 } /* end else if */32 else if ( rowPosition == size ) {33 printf( "*" );34 } /* end else if */35 else { /* otherwise, print a space */36 printf( " " );37 } /* end else */3839 --rowPosition; /* decrement row counter */40 } /* end inner while */4142 printf( "\n" ); /* new line for next row */43 --side; /* decrement side counter */44 } /* end outer while */4546 return 0; /* indicate successful termination */4748 } /* end main */

Page 23: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 41

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

3.35 A palindrome is a number or a text phrase that reads the same backwards as forwards. For example, each of the followingfive-digit integers are palindromes: 12321, 55555, 45554 and 11611. Write a program that reads in a five-digit integer and deter-mines whether or not it is a palindrome. [Hint: Use the division and remainder operators to separate the number into its individualdigits.]

ANS:

1 /* Exercise 3.35 Solution */2 #include<stdio.h>34 int main()5 { 6 int number; /* input number */7 int temp1; /* first temporary integer */8 int temp2; /* second temporary integer */9 int firstDigit; /* first digit of input */

10 int secondDigit; /* second digit of input */11 int fourthDigit; /* fourth digit of input */12 int fifthDigit; /* fifth digit of input */1314 printf( "Enter a five-digit number: " ); /* get number */15 scanf( "%d", &number );1617 temp1 = number;1819 /* determine first digit by integer division by 10000 */20 firstDigit = temp1 / 10000;21 temp2 = temp1 % 10000;2223 /* determine second digit by integer division by 1000 */24 secondDigit = temp2 / 1000;25 temp1 = temp2 % 1000;2627 temp2 = temp1 % 100;2829 /* determine fourth digit by integer division by 10 */30 fourthDigit = temp2 / 10;31 temp1 = temp2 % 10;3233 fifthDigit = temp1;3435 /* if first and fifth digits are equal */36 if ( firstDigit == fifthDigit ) {3738 /* if second and fourth digits are equal */39 if ( secondDigit == fourthDigit ) {4041 /* number is a palindrome */42 printf( "%d is a palindrome\n", number );43 } /* end if */44 else { /* number is not a palindrome */45 printf( "%d is not a palindrome\n", number );46 } /* end else */4748 } /* end if */49 else { /* number is not a palindrome */ 50 printf( "%d is not a palindrome\n", number );51 } /* end else */5253 return 0; /* indicate successful termination */5455 } /* end main */

Page 24: Chapter 3 Solutions

42 Structured Program Development in C: Solutions Chapter 3

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

3.36 Input an integer containing only 0s and 1s (i.e., a “binary” integer) and print its decimal equivalent. [Hint: Use the remainderand division operators to pick off the “binary” number’s digits one at a time from right to left. Just as in the decimal number systemin 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, then8, 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:

Enter a five-digit number: 1818118181 is a palindrome

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

1 /* Exercise 3.36 Solution */2 #include<stdio.h>34 int main()5 { 6 int binary; /* current value of binary number */7 int number; /* input binary number */8 int decimal = 0; /* current value of decimal number */9 int highBit = 16; /* value of highest bit */

10 int factor = 10000; /* factor of 10 to pick off digits */1112 /* prompt for binary input */13 printf( "Enter a binary number ( 5 digits maximum ): " );14 scanf( "%d", &binary );1516 number = binary; /* save in number for final display */1718 /* loop 5 times using powers of 2 */19 while ( highBit >= 1 ) { 2021 /* update decimal value with decimal value corresponding22 to current highest binary bit */23 decimal += binary / factor * highBit;2425 /* reduce high bit by factor of 2, i.e., 26 move one bit to the right */27 highBit /= 2;2829 /* reduce binary number to eliminate current highest bit */30 binary %= factor;3132 /* reduce factor by power of 10, i.e.,33 move one bit to the right */34 factor /= 10;35 } /* end while */3637 /* display decimal value */38 printf( "The decimal equivalent of %d is %d\n", number, decimal );3940 return 0; /* indicate successful termination */4142 } /* end main */

Page 25: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 43

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

3.37 How can you determine how fast your own computer really operates? Write a program with a while loop that counts from1 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 totime how long each million repetitions of the loop takes.

ANS:

3.38 Write a program that prints 100 asterisks, one at a time. After every tenth asterisk, your program should print a newlinecharacter. (Hint: Count from 1 to 100. Use the remainder operator to recognize each time the counter reaches a multiple of 10.)

ANS:

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

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

1 /* Exercise 3.37 Solution */2 #include<stdio.h>34 int main()5 { 6 long int count = 1; /* counter */78 /* loop to 300,000,000 */9 while( count <= 300000000 ) {

1011 if ( count % 100000000 == 0 ) {12 printf( "Multiple is %d\n", count / 100000000 );13 } /* end if */1415 ++count; /* increment count */16 } /* end while */1718 return 0; /* indicate successful termination */1920 } /* end main */

Multiple is 1Multiple is 2Multiple is 3

1 /* Exercise 3.38 Solution */2 #include <stdio.h>34 int main()5 { 6 int count = 0; /* counter */78 /* loop to 100 */9 while( ++count <= 100 )

1011 /* print a new line after every 10th asterisk */12 count % 10 == 0 ? printf( "*\n" ) : printf( "*" );1314 return 0; /* indicate successful termination */

Page 26: Chapter 3 Solutions

44 Structured Program Development in C: Solutions Chapter 3

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

3.39 Write a program that reads an integer and determines and prints how many digits in the integer are 7s.ANS:

1516 } /* end main */

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

1 /* Exercise 3.39 Solution */2 #include <stdio.h>34 int main()5 { 6 int number; /* user input */7 int numCopy; /* copy of number */8 int factor = 10000; /* set factor to pick off digits */9 int digit; /* individual digit of number */

10 int sevens = 0; /* sevens counter */1112 printf( "Enter a 5-digit number: " ); /* get number from user */13 scanf( "%d", &number );1415 numCopy = number;1617 /* loop through each of the 5 digits */18 while ( factor >= 1 ) { 19 digit = numCopy / factor; /* pick off next digit */2021 if ( digit == 7 ) { /* if digit equals 7, increment sevens */22 ++sevens;23 } /* end if */2425 numCopy %= factor;26 factor /= 10;27 } /* end while */2829 /* output number of sevens */30 printf( "The number %ld has %d seven(s) in it\n", number, sevens );3132 return 0; /* indicate successful termination */3334 } /* end main */

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

Page 27: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 45

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

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:

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

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

1 /* Exercise 3.40 Solution */2 #include <stdio.h>34 int main()5 { 6 int side = 8; /* side counter */7 int row; /* row counter */8 int mod; /* remainder */9

10 /* loop 8 times */11 while ( side >= 1 ) { 12 row = 8; /* reset row counter */13 mod = side % 2;1415 /* loop 8 times */16 while ( row >= 1 ) {17 18 /* if odd row, begin with a space */19 if ( mod != 0 ) { 20 printf( " " );21 mod = 0;22 } /* end if */2324 printf( "* " );25 --row;26 } /* end while */2728 printf( "\n" ); /* go to next line */29 --side;30 } /* end while */3132 return 0; /* indicate successful termination */3334 } /* end main */

Page 28: Chapter 3 Solutions

46 Structured Program Development in C: Solutions Chapter 3

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

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 notterminate (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 max-imum value for an integer is exceeded. On a 4-byte system, the largest integer value is 2147483647 and anything abovethat is represented by a negative number, which fails the loop continuation test).

3.42 Write a program that reads the radius of a circle (as a float value) and computes and prints the diameter, the circumferenceand the area. Use the value 3.14159 for π.

1 /* Exercise 3.41 Solution */2 #include <stdio.h>34 int main()5 { 6 int multiple = 1; /* counter */78 /* infinite loop */9 while ( multiple > 0 ) {

1011 /* calculate the next power of two */12 multiple *= 2;13 printf( "%d\n", multiple );14 } /* end while */1516 return 0; /* indicate successful termination */1718 } /* end main */

248163264128256512102420484096819216384327686553613107226214452428810485762097152419430483886081677721633554432671088641342177282684354565368709121073741824-2147483648

Page 29: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 47

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

ANS:

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

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

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

3.44 Write a program that reads three nonzero float values and determines and prints if they could represent the sides of a tri-angle.

ANS:

1 /* Exercise 3.42 Solution */2 #include<stdio.h>34 int main()5 { 6 float radius; /* input radius */7 float pi = 3.14159; /* value for pi */89 printf( "Enter the radius: "); /* get radius value */

10 scanf( "%f", &radius );1112 /* compute and display diameter */13 printf( "The diameter is %.2f\n", radius * 2 );1415 /* compute and display circumference */16 printf( "The circumference is %.2f\n", 2 * pi * radius );1718 /* compute and display area */19 printf( "The area is %.2f\n", pi * radius * radius );2021 return 0; /* indicate successful termination */2223 } /* end main */

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

1 /* Exercise 3.44 Solution */2 #include <stdio.h>34 int main()5 { 6 double a; /* first number */7 double b; /* second number */8 double c; /* third number */9

10 /* input 3 numbers */11 printf( "Enter three doubleing point numbers: " );12 scanf( "%lf%lf%lf", &a, &b, &c);1314 /* use Pythagorean Theorem */15 if ( c * c == a * a + b * b ) {16 printf( "The three numbers could be sides of a triangle\n" );17 } /* end if */

Page 30: Chapter 3 Solutions

48 Structured Program Development in C: Solutions Chapter 3

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

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

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

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

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

1 /* Exercise 3.45 Solution */2 #include <stdio.h>34 int main()5 { 6 int a; /* first number */7 int b; /* second number */8 int c; /* third number */9

10 /* input three numbers */11 printf( "Enter three integers: ");12 scanf( "%d%d%d", &a, &b, &c );1314 /* use Pythagorean Theorem */15 if ( c * c == a * a + b * b ) {16 printf( "The three integers are the sides of"); 17 printf( " a right triangle\n" );18 } /* end if */19 else {20 printf( "The three integers are not the sides"); 21 printf( " of a right triangle\n" );22 } /* end else */2324 return 0; /* indicate successful termination */2526 } /* end main */

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

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

Page 31: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 49

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

3.46 A company wants to transmit data over the telephone, but they are concerned that their phones may be tapped. All of theirdata is transmitted as four-digit integers. They have asked you to write a program that will encrypt their data so that it may be trans-mitted more securely. Your program should read a four-digit integer and encrypt it as follows: Replace each digit by the remainderafter (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 theoriginal number.

ANS:

1 /* Exercise 3.46 Part A solution */2 #include <stdio.h>34 int main()5 { 6 int first; /* first digit replacement */7 int second; /* second digit replacement */8 int third; /* third digit replacement */9 int fourth; /* fourth digit replacement */

10 int digit; /* input number */11 int temp1; /* temporarily hold digit */12 int temp2; /* temporarily hold digit */13 int encryptedNumber; /* resulting encrypted number */1415 /* prompt for input */16 printf( "Enter a four digit number to be encrypted: " );17 scanf( "%d", &digit );1819 temp1 = digit;2021 /* retrieve each digit and replace with 22 (sum of digit and 7) mod 10 */23 first = ( temp1 / 1000 + 7 ) % 10;24 temp2 = temp1 % 1000;2526 second = ( temp2 / 100 + 7 ) % 10;27 temp1 = temp2 % 100;2829 third = ( temp1 / 10 + 7 ) % 10;30 temp2 = temp1 % 10;3132 fourth = ( temp2 + 7 ) % 10;3334 /* swap first and third */35 temp1 = first;36 first = third * 1000; /* multiply by 1000 for 1st digit component */37 third = temp1 * 10; /* multiply by 10 for 3rd digit component */38 39 /* swap second and fourth */40 temp1 = second;41 second = fourth * 100; /* multiply by 100 for 2nd digit component */42 fourth = temp1 * 1;4344 /* add components to obtain encrypted number */45 encryptedNumber = first + second + third + fourth;4647 /* display encrypted number */48 printf( "Encrypted number is %d\n", encryptedNumber );4950 return 0; /* indicate successful termination */5152 } /* end main */

Page 32: Chapter 3 Solutions

50 Structured Program Development in C: Solutions Chapter 3

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

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

1 /* Exercise 3.46 Part B Solution */2 #include <stdio.h>34 int main()5 { 6 int first; /* first decrypted digit */7 int second; /* second decrypted digit */8 int third; /* third decrypted digit */9 int fourth; /* fourth decrypted digit */

10 int decrypted; /* decrypted number */11 int temp1; /* temporarily hold digit */12 int temp2; /* temporarily hold digit */13 int encryptedNumber; /* input number */1415 /* prompt for input */16 printf( "Enter a four digit encrypted number: " );17 scanf( "%d", &encryptedNumber );1819 temp1 = encryptedNumber;2021 /* retrieve each digit and decrypt by 22 (sum of digit and 3) mod 10 */23 first = ( temp1 / 1000 );24 temp2 = temp1 % 1000;2526 second = ( temp2 / 100 );27 temp1 = temp2 % 100;2829 third = ( temp1 / 10 );30 temp2 = temp1 % 10;3132 fourth = temp2;3334 temp1 = ( first + 3 ) % 10;35 first = ( third + 3 ) % 10;36 third = temp1;3738 temp1 = ( second + 3 ) % 10;39 second = ( fourth + 3 ) % 10;40 fourth = temp1;4142 /* add components to obtain decrypted number */43 decrypted = ( first * 1000 ) + ( second * 100 ) + 44 ( third * 10 ) + fourth;4546 /* display decrypted number */47 printf( "Decrypted number is %d\n", decrypted );4849 return 0; /* indicate successful termination */5051 } /* end main */

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

Page 33: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 51

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

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

andn! = 1 (for n = 0).

For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. a) Write a program that reads a nonnegative integer and computes and prints its factorial.ANS:

1 /* Exercise 3.47 Part A Solution */2 #include <stdio.h>34 int main()5 { 6 int n; /* current multiplication factor */7 int number = -1; /* input number */8 unsigned factorial = 1; /* resulting factorial */9

10 /* loop until valid input */11 do { 12 printf( "Enter a positive integer: " );13 scanf( "%d", &number );14 } while ( number < 0 ); /* end do...while */1516 n = number;1718 /* compute factorial */19 while( n >= 0 ) { 2021 if ( n == 0 ) {22 factorial *= 1;23 } /* end if */24 else {25 factorial *= n;26 } /* end else */2728 --n;29 } /* end while */3031 /* display factorial */32 printf( "%d! is %u\n", number, factorial );3334 return 0; /* indicate successful termination */3536 } /* end main */

Enter a positive integer: 55! is 120

Enter a positive integer: 99! is 362880

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

Page 34: Chapter 3 Solutions

52 Structured Program Development in C: Solutions Chapter 3

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

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

ANS:

c) Write a program that computes the value of ex by using the formula

ANS:

e 1 11!----- 1

2!----- 1

3!----- …+ + + +=

1 /* Exercise 3.47 Part B Solution */2 #include <stdio.h>34 int main()5 { 6 int n = 0; /* loop counter for accuracy */7 int fact = 1; /* current n factorial */8 int accuracy = 10; /* degree of accuracy */9 double e = 0; /* current estimated value of e */

1011 /* loop until degree of accuracy */12 while( n <= accuracy ) { 1314 if ( n == 0 ) {15 fact *= 1;16 } /* end if */17 else {18 fact *= n;19 } /* end else */2021 e += 1.0 / fact;22 ++n;23 } /* end while */2425 printf( "e is %f\n", e ); /* display estimated value */2627 return 0; /* indicate successful termination */2829 } /* end main */

e is 2.718282

ex 1 x1!----- x2

2!----- x3

3!----- …+ + + +=

1 /* Exercise 3.47 Part C Solution */2 #include <stdio.h>34 int main()5 { 6 int n = 0; /* counter */7 int accuracy = 15; /* degree of accuracy */8 int x = 3; /* exponent */9 int times = 0; /* counter */

10 int count; /* copy of n */11 double e = 1.0; /* e raised to the x power */12 double exp = 0.0; /* x raised to the n power */13 double fact = 1.0; /* n factorial */14

Page 35: Chapter 3 Solutions

Chapter 3 Structured Program Development in C: Solutions 53

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

15 /* loop while less than degree of accuracy */16 while( n <= accuracy ) { 17 count = n;1819 /* update n! */20 if ( n == 0 ) {21 fact *= 1.0;22 } /* end if */23 else {24 fact *= n;25 } /* end else */2627 while ( times < count ) { 28 29 /* calculate x raised to the n power */30 if ( times == 0 ) { 31 exp = 1.0;32 exp *= x;33 } /* end if */34 else {35 exp *= x;36 } /* end else */3738 ++times;39 } /* end while */4041 e += exp / fact; /* update e raised to the x power */42 ++n;43 } /* end while */44 45 /* display result */46 printf( "e raised to the %d power is %f\n", x, e );4748 return 0; /* indicate successful termination */4950 } /* end main */

e raised to the 3 power is 20.085534

Page 36: Chapter 3 Solutions

54 Structured Program Development in C: Solutions Chapter 3

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