Académique Documents
Professionnel Documents
Culture Documents
3 Structured Program
Development in C: Solutions
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 55 Thursday, November 12, 2009 6:19 PM
Self-Review Exercises 55
Self-Review Exercises
3.1 Fill in the blanks in each of the following questions.
a) A procedure for solving a problem in terms of the actions to be executed and the order
in which the actions should be executed is called a(n) .
ANS: algorithm.
b) Specifying the execution order of statements by the computer is called .
ANS: program control.
c) All programs can be written in terms of three types of control statements: ,
and .
ANS: sequence, selection, repetition.
d) The selection statement is used to execute one action when a condition is
true and another action when that condition is false.
ANS: if...else.
e) Several statements grouped together in braces ({ and }) are called a(n) .
ANS: compound statement.
f) The repetition statement specifies that a statement or group of statements
is to be executed repeatedly while some condition remains true.
ANS: while.
g) Repetition of a set of instructions a specific number of times is called rep-
etition.
ANS: counter-controlled.
h) When it is not known in advance how many times a set of statements will be repeated,
a(n) value can be used to terminate the repetition.
ANS: sentinel.
3.2 Write four different C statements that each add 1 to integer variable x.
ANS: x = x + 1;
x += 1;
++x;
x++;
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 56 Thursday, November 12, 2009 6:19 PM
3.6 Determine the values of variables product and x after the following calculation is per-
formed. Assume that product and x each have the value 5 when the statement begins executing.
product *= x++;
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 57 Thursday, November 12, 2009 6:19 PM
Self-Review Exercises 57
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 58 Thursday, November 12, 2009 6:19 PM
ANS: Error: Semicolon after the else part of the if…else statement results in a logic error.
The second printf will always be executed.
Correction: Remove the semicolon after else.
3.10 What is wrong with the following while repetition statement (assume z has value 100),
which is supposed to calculate the sum of the integers from 100 down to 1:
while ( z >= 0 )
sum += z;
ANS: The value of the variable z is never changed in the while statement. Therefore, an
infinite loop is created. To prevent the infinite loop, z must be decremented so that
its value eventually becomes less than zero.
Exercises
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; /* total not originally initialized */
while ( x <= 10 ) {
total += x;
++x;
}
c) While ( x <= 100 )
total += x;
++x;
ANS:
while ( x <= 100 ) { /* while changed to lowercase */
total += x;
++x;
} /* } added */
d) while ( y > 0 ) {
printf( "%d\n", y );
++y;
}
ANS:
while ( y > 0 ) {
printf( "%d\n", y );
--y; /* ++ changed to --, loop never ends otherwise */
}
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 59 Thursday, November 12, 2009 6:19 PM
Exercises 59
1 #include <stdio.h>
2
3 int main( void )
4 {
5 int x = 1, total = 0, y;
6
7 while ( x <= 10 ) {
8 y = x * x;
9 printf( "%d\n", y );
10 total += y;
11 ++x;
12 }
13
14 printf("Total is %d\n", total);
15 return 0;
16 }
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 60 Thursday, November 12, 2009 6:19 PM
ANS:
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) 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 + z
c) 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 number
Input the second number
Add the two numbers
Output 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 keyboard
Input the second number from the keyboard
If the first number is greater than the second number
Print it
Else if the second number is greater than the first number
Print it
Else
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 that the user types the sentinel value -1 to indicate “end
of data entry.”
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 61 Thursday, November 12, 2009 6:19 PM
Exercises 61
ANS:
Input a value from the 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 a working C program.
ANS: False. The algorithm is the hardest part 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.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 62 Thursday, November 12, 2009 6:19 PM
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. Keep track of the total miles and the total gallons.
Second refinement:
Initialize totalGallons to zero
Initialize totalMiles to zero
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 63 Thursday, November 12, 2009 6:19 PM
Exercises 63
23
24 /* display miles per gallon for current tank */
25 printf( "The miles / gallon for this tank was %f\n\n",
26 miles / gallons );
27
28 /* get next tank's gallons */
29 printf( "Enter the gallons used ( -1 to end ): " );
30 scanf( "%f", &gallons );
31 } /* end while */
32
33 /* calculate average miles per gallon over all tanks */
34 totalAverage = totalMiles / totalGallons;
35 printf("\nThe overall average miles / gallon was %f\n", totalAverage );
36 return 0; /* indicate successful termination */
37 } /* 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:
a) Account number
b) Balance at the beginning of the month
c) Total of all items charged by this customer this month
d) Total of all credits applied to this customer's account this month
e) Allowed credit limit
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 num-
ber, credit limit, new balance and the message “Credit limit exceeded.” Here is a sample input/out-
put dialog:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 64 Thursday, November 12, 2009 6:19 PM
ANS:
2)Top:
Determine if each of an arbitrary number of department store customers has exceed-
ed the credit limit on a charge account
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 bal-
ance exceeds the credit limit. Then process the next customer.
Second refinement:
Input the first customer’s account 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 charges
Input the customer’s total credits
Input the customer’s credit limit
Calculate the customer’s new balance
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 65 Thursday, November 12, 2009 6:19 PM
Exercises 65
23
24 printf( "Enter total credits: " );
25 scanf( "%f", &credits );
26
27 printf( "Enter credit limit: " );
28 scanf( "%f", &limit );
29
30 balance += charges - credits; /* calculate balance */
31
32 /* if balance is over limit, display account number
33 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 */
39
40 /* prompt for next account */
41 printf( "\nEnter account number ( -1 to end ): " );
42 scanf( "%d", &accountNumber );
43 } /* end while */
44
45 return 0; /* indicate successful termination */
46 } /* end main */
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. De-
velop a program that will input each salesperson’s gross sales for last week and will calculate and dis-
play that 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 process the next salesperson
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 66 Thursday, November 12, 2009 6:19 PM
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 week
Print the salesperson’s wages for the week
Input the next salesperson’s sales in dollars
3)
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
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 67 Thursday, November 12, 2009 6:19 PM
Exercises 67
loans, and will calculate and display the simple interest for each loan, 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 interest for 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 rate
Input the term of the loan in days
Calculate the simple interest for the loan
Print the simple interest for the loan
Input the loan principal for the next loan
3)
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 68 Thursday, November 12, 2009 6:19 PM
3.21 Develop a program that will determine the gross pay for 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 com-
pany, 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:
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 the employee’s gross pay, and process the next employee
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 69 Thursday, November 12, 2009 6:19 PM
Exercises 69
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 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 for the next employee
3)
3.22 Write a program that demonstrates the difference between predecrementing and post-
decrementing using the decrement operator --.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 70 Thursday, November 12, 2009 6:19 PM
ANS:
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 three spaces between numbers.
ANS:
1 2 3 4 5 6 7 8 9 10
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 71 Thursday, November 12, 2009 6:19 PM
Exercises 71
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 sold
the most units wins the contest. Write a pseudocode program and then a program that inputs a se-
ries of 10 numbers and determines and prints the largest of the numbers. [Hint: Your program
should use three variables as follows]:
counter: A counter to count to 10 (i.e., to keep track of how many numbers have
been input and to determine when all 10 numbers have been processed)
number: The current number input to the program
largest: The largest number found so far
ANS:
Input the first number directly into the variable largest
Increment counter to 2
Print the value of the largest (while condition false when counter is 11)
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 72 Thursday, November 12, 2009 6:19 PM
3.25 Write a program that utilizes looping to print the following table of values:
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
The tab escape sequence, \t, may be used in the printf statement to separate the columns with
tabs.
ANS:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 73 Thursday, November 12, 2009 6:19 PM
Exercises 73
3.26 Write a program that utilizes looping to produce the following table of values:
3 5 7 9
6 8 10 12
9 11 13 15
12 14 16 18
15 17 19 21
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 number only once.]
ANS:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 74 Thursday, November 12, 2009 6:19 PM
14 counter = 2;
15
16 /* loop 9 more times */
17 while ( counter <= 10 ) {
18 printf( "Enter next number: " ); /* prompt for next number */
19 scanf( "%d", &number );
20
21 /* if current number is greater than largest */
22 if ( number > largest ) {
23
24 /* update second largest with previous largest */
25 secondLargest = largest;
26
27 /* update largest with current number */
28 largest = number;
29 } /* end if */
30 else {
31
32 /* if number is between secondLargest and largest */
33 if ( number > secondLargest ) {
34 secondLargest = number;
35 } /* end if */
36
37 } /* end else */
38
39 ++counter;
40 } /* end while */
41
42 /* display largest two numbers */
43 printf( "Largest is %d\n", largest );
44 printf( "Second largest is %d\n", secondLargest );
45
46 return 0; /* indicate successful termination */
47
48 } /* end main */
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 looping until the user enters a correct value.
ANS:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 75 Thursday, November 12, 2009 6:19 PM
Exercises 75
3
4 int main( void )
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 ) {
13
14 /* prompt user for input and obtain value from user */
15 printf( "Enter result ( 1=pass, 2=fail ): " );
16 scanf( "%d", &result );
17
18 /* if result 1, increment passes */
19 if ( result == 1 ) {
20 ++passes;
21 ++student;
22 } /* end if */
23 else if ( result == 2 ) { /* if result is 2, increment failures */
24 ++failures;
25 ++student;
26 } /* end else if */
27 else { /* if result is not 1 or 2, result is invalid */
28 printf( "Invalid result\n" );
29 } /* end else */
30
31 } /* end while */
32
33 printf( "Passed %d\nFailed %d\n", passes, failures );
34
35 /* if more than eight students passed, print "raise tuition" */
36 if ( passes > 8 ) {
37 printf( "Raise tuition\n" );
38 } /* end if */
39
40 return 0; /* indicate successful termination */
41 } /* end main */
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 76 Thursday, November 12, 2009 6:19 PM
1 #include <stdio.h>
2
3 /* function main begins program execution */
4 int main( void )
5 {
6 int count = 1; /* initialize count */
7
8 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 */
14
15 return 0; /* indicate program ended successfully */
16 } /* end function main */
ANS:
****
++++++++
****
++++++++
****
++++++++
****
++++++++
****
++++++++
1 #include <stdio.h>
2
3 /* function main begins program execution */
4 int main( void )
5 {
6 int row = 10; /* initialize row */
7 int column; /* define column */
8
9 while ( row >= 1 ) { /* loop until row < 1 */
10 column = 1; /* set column to 1 as iteration begins */
11
12 while ( column <= 10 ) { /* loop 10 times */
13 printf( "%s", row % 2 ? "<": ">" ); /* output */
14 column++; /* increment column */
15 } /* end inner while */
16
17 row--; /* decrement row */
18 printf( "\n" ); /* begin new output line */
19 } /* end outer while */
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 77 Thursday, November 12, 2009 6:19 PM
Exercises 77
20
21 return 0; /* indicate program ended successfully */
22 } /* end function main */
ANS:
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
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 place-
ment of braces {}. Because, on first glance, you may not be sure which if an else matches, this is
referred to as the “dangling else” problem. We eliminated the indentation from the following code
to make the problem more challenging. [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, y = 9
$$$$$
b) if ( x < 10 ) {
if ( y > 10 )
printf( "*****\n" );
}
else {
printf( "#####\n" );
printf( "$$$$$\n" );
}
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 78 Thursday, November 12, 2009 6:19 PM
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 may not make any changes other than inserting braces. The
compiler ignores the indentation in a program. We 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" );
@@@@@
$$$$$
&&&&&
ANS:
if ( y == 8 ) {
if ( x == 5 )
printf( "@@@@@\n" );
else
printf( "#####\n" );
printf( "$$$$$\n" );
printf( "&&&&&\n" );
}
@@@@@
ANS:
if ( y == 8 )
if ( x == 5 )
printf( "@@@@@\n" );
else {
printf( "#####\n" );
printf( "$$$$$\n" );
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 79 Thursday, November 12, 2009 6:19 PM
Exercises 79
printf( "&&&&&\n" );
}
@@@@@
&&&&&
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 a compound statement.]
#####
$$$$$
&&&&&
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 aster-
isks. 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
****
****
****
****
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 80 Thursday, November 12, 2009 6:19 PM
ANS:
3.34 Modify the program you wrote in Exercise 3.33 so that it prints a hollow square. For exam-
ple, if your program reads a size of 5, it should print
*****
* *
* *
* *
*****
ANS:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 81 Thursday, November 12, 2009 6:19 PM
Exercises 81
3.35 A palindrome is a number or a text phrase that reads the same backward as forward. For
example, each of the following five-digit integers is a palindrome: 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 remainder operators to separate the number into its individual digits.]
ANS:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 82 Thursday, November 12, 2009 6:19 PM
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 83 Thursday, November 12, 2009 6:19 PM
Exercises 83
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,
and so on, 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, and so on. 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:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 84 Thursday, November 12, 2009 6:19 PM
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 100 million
repetitions of the loop takes.
ANS:
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 pro-
gram 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:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 85 Thursday, November 12, 2009 6:19 PM
Exercises 85
8 /* loop to 100 */
9 while( ++count <= 100 )
10
11 /* print a new line after every tenth asterisk */
12 count % 10 == 0 ? printf( "*\n" ) : printf( "*" );
13
14 return 0; /* indicate successful termination */
15 } /* end main */
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
3.39 Write a program that reads an integer and determines and prints how many digits in the
integer are 7s.
ANS:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 86 Thursday, November 12, 2009 6:19 PM
31 factor /= 10;
32 } /* end while */
33
34 /* output number of sevens */
35 printf( "The number %d has %d seven(s) in it\n", number, sevens );
36
37 return 0; /* indicate successful termination */
38 } /* end main */
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
Your program must use only three output statements, one of each of the following forms:
printf( "* " );
printf( " " );
printf( "\n" );
ANS:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 87 Thursday, November 12, 2009 6:19 PM
Exercises 87
18 /* loop 8 times */
19 while ( col < 8 ) {
20 printf( "* " );
21 ++col;
22 } /* end while */
23
24 printf( "\n" ); /* go to next line */
25 ++row;
26 } /* end while */
27
28 return 0; /* indicate successful termination */
29
30 } /* end main */
3.41 Write a program that keeps printing the multiples of the integer 2, namely 2, 4, 8, 16, 32,
64, and so on. Your loop should not terminate (i.e., you should create an infinite loop). What hap-
pens when you run this program?
ANS: Program execution terminates when largest integer is exceeded. (That is, the loop
continuation test fails when the maximum value for an integer is exceeded. On a 4-
byte system, the largest integer value is 2147483647 and anything above that is rep-
resented by a negative number, which fails the loop continuation test.)
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 88 Thursday, November 12, 2009 6:19 PM
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 π.
ANS:
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 89 Thursday, November 12, 2009 6:19 PM
Exercises 89
3.43 What is wrong with the following statement? Rewrite the statement to accomplish what the
programmer was probably trying to do.
printf( "%d", ++( x + y ) );
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 90 Thursday, November 12, 2009 6:19 PM
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:
3.46 The factorial of a nonnegative integer n is written n! (pronounced “n factorial”) and is de-
fined as follows:
n! = n · (n - 1) · (n - 2) · … · 1 (for values of n greater than or equal to 1)
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 and computes and prints its factorial.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 91 Thursday, November 12, 2009 6:19 PM
Exercises 91
ANS:
b) Write a program that estimates the value of the mathematical constant e by using the
formula:
1 1 1
e = 1 + ----- + ----- + ----- + …
1! 2! 3!
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 92 Thursday, November 12, 2009 6:19 PM
ANS:
e is 2.718282
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.
chtp6_03_IM.fm Page 93 Thursday, November 12, 2009 6:19 PM
Making a Difference 93
16 denominator *= n;
17 e += numerator / denominator;
18 ++n;
19 }
20
21 printf( "e raised to the %d power is %f\n", x, e ); /* display value */
22
23 return 0; /* indicate successful termination */
24
25 } /* end main */
Making a Difference
3.47 (World Population Growth Calculator) Use the web to determine the current world pop-
ulation and the annual world population growth rate. Write an application that inputs these values,
then displays the estimated world population after one, two, three, four and five years.
ANS: See the answer in the file WorldPop.c with this chapter’s solutions.
3.48 (Target-Heart-Rate Calculator) While exercising, you can use a heart-rate monitor to see
that your heart rate stays within a safe range suggested by your trainers and doctors. According to the
American Heart Association (AHA) (www.americanheart.org/presenter.jhtml?identifier=4736),
the formula for calculating your maximum heart rate in beats per minute is 220 minus your age in
years. Your target heart rate is a range that is 50–85% of your maximum heart rate. [Note: These for-
mulas are estimates provided by the AHA. Maximum and target heart rates may vary based on the
health, fitness and gender of the individual. Always consult a physician or qualified health care pro-
fessional before beginning or modifying an exercise program.] Create a program that reads the user’s
birthday and the current day (each consisting of the month, day and year). Your program should cal-
culate and display the person’s age (in years), the person’s maximum heart rate and the person’s target
heart rate range.
ANS: See the answer in the file TargetHeartRate.c with this chapter’s solutions.
3.49 (Enforcing Privacy with Cryptography) The explosive growth of Internet communications
and data storage on Internet-connected computers has greatly increased privacy concerns. The field
of cryptography is concerned with coding data to make it difficult (and hopefully—with the most
advanced schemes—impossible) for unauthorized users to read. In this exercise you’ll investigate a
simple scheme for encrypting and decrypting data. A company that wants to send data over the In-
ternet has asked you to write a program that will encrypt it so that it may be transmitted more se-
curely. All the data is transmitted as four-digit integers. Your application should read a four-digit
integer entered by the user and encrypt it as follows: Replace each digit with the result of adding 7
to the digit and getting the remainder after dividing the new value 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 application that inputs an encrypted four-digit integer and decrypts it (by reversing the
encryption scheme) to form the original number. [Optional reading project: Research “public key
cryptography” in general and the PGP (Pretty Good Privacy) specific public key scheme. You may
also want to investigate the RSA scheme, which is widely used in industrial-strength applications.]
ANS: See the answer in the files Cryptography.c and ReverseCryptography.c with this
chapter’s solutions.
© 2010 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved.