Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

For Exercises 5.17-5.20, Perform Each of The Following Steps

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

226 Chapter 5 Algorithm Development and Control Statements: Part 1

For Exercises 5.17–5.20, perform each of the following steps:


a) Read the problem statement.
b) Formulate the algorithm using pseudocode and top-down, stepwise refinement.
c) Write a C# app.
d) Test, debug and execute the C# app.
e) Process three complete sets of data.
5.17 (Interest on Term Deposit) Investors are concerned with the interest their investments earn
in one month. One investor has kept track of the interest earned on several investments by recording
the amount of each investment and the interest earned on each. Develop a C# app that will input
the amount invested and the interest earned (both as integers) for each investment. The app should
calculate and display the combined interests earned for each investment up to the current month.
The results are rounded off to the nearest hundredth. Use the Console class’s ReadLine method and
sentinel-controlled iteration to obtain the data from the user.
5.18 (Inventory Level Calculator) Develop a C# app that will determine whether the level of any
of the items in a store’s inventory has fallen below 1% of the initial number of units. For each in-
ventory item, the following facts are available:
a) the item’s code
b) the initial number of units
c) the number of units purchased
d) the number of units issued
The app should input all these facts as integers, calculate the closing number of units (= opening
number of units +number of units purchased - number of units issued), display the closing number of
units and determine whether the closing number of units has fallen below the lower limit. For those
items whose quantity has fallen below the lower limit, the app should display the message “Procure
more units immediately”. Use sentinel-controlled iteration to obtain the data for each item.
5.19 (Sales-Commission Calculator) A large 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 $5,000 worth of merchandise in a week receives $200 plus 9% of $5,000, or
a total of $650. You’ve been supplied with a list of the items sold by each salesperson. The values of
these items are as follows:
Item Value
1 239.99
2 129.75
3 99.95
4 350.89

Develop a C# app that inputs one salesperson’s items sold for the last week, then calculates and dis-
plays that salesperson's earnings. There’s no limit to the number of items that can be sold by a
salesperson.
5.20 (Discount Calculator) Develop a C# app that will determine the net amount payable for
items purchased at a departmental store. The store offers a 10% discount if the total purchase value
is less than or equal to $5,000 and an additional 10% on purchase amounts exceeding $5,000. The
app should input the price of each item purchased, calculate the total purchase value, the amount
of discount applicable, and the net amount payable by the customer, and display the results. Use
the Console class’s ReadLine method to input the data.
5.21 (Find the Largest Number) The process of finding the maximum value (i.e., the largest of
a group of values) is used frequently in computer applications. For example, an app that determines
the winner of a sales contest would input the number of units sold by each salesperson. The sales-
Exercises 227

person who sells the most units wins the contest. Write pseudocode, then a C# app that inputs a
series of 10 integers, then determines and displays the largest integer. Your app should use at least
the following three variables:
a) 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).
b) number: The integer most recently input by the user.
c) largest: The largest number found so far.

5.22 (Tabular Output) Write a C# app that uses looping to display the following table of values:

N N^2 N^3 N^2 + N^3

10 100 1000 1100


20 400 8000 8400
30 900 27000 27900
40 1600 64000 65600
50 2500 125000 127500
Press any key to continue . . .

5.23 (Find the Two Largest Numbers) Using an approach similar to that for Exercise 5.21, find
the two largest values of the 10 values entered. [Note: You may input each number only once.]

5.24 (Validating User Input) Modify the app in Fig. 5.13 to validate its inputs. For any input,
if the value entered is other than 1 or 2, display the message “Invalid input,” then keep looping until
the user enters a correct value.

5.25 (What Does This Program Do?) What does the following app display?

1 // Ex. 5.25: Mystery2.cs


2 using System;
3
4 class Mystery2
5 {
6 public static void Main()
7 {
8 int number = 50;
9 while (number >= 40)
10 {
11 Console.WriteLine(number * 100/50 > 90? "A*" : "B");
12 --number;
13 }
14 }
15 }

5.26 (What Does This Program Do?) What does the following app display?

1 // Ex. 5.26: Mystery3.cs


2 using System;
3
4 class Mystery3
5 {
6 static void Main()
7 {
8 int row = 10;
9 int column;
10 (continued…)
228 Chapter 5 Algorithm Development and Control Statements: Part 1

11 while (row >= 1)


12 {
13 column = 1;
14
15 while (column <= 10)
16 {
17 Console.Write(row % 2 == 1 ? "<" : ">");
18 ++column;
19 }
20
21 --row;
22 Console.WriteLine();
23 }
24 }
25 }

5.27 (Dangling-else Problem) The C# compiler always associates an else with the immediately
preceding if unless told to do otherwise by the placement of braces ({ and }). This behavior can
lead to what is referred to as the dangling-else problem. The indentation of the nested statement
if (x > 5)
if (y > 5)
Console.WriteLine("x and y are > 5");
else
Console.WriteLine("x is <= 5");

appears to indicate that if x is greater than 5, the nested if statement determines whether y is also
greater than 5. If so, the statement outputs the string "x and y are > 5". Otherwise, it appears that
if x is not greater than 5, the else part of the if…else outputs the string "x is <= 5". Beware! This
nested if…else statement does not execute as it appears. The compiler actually interprets the
statement as
if (x > 5)
if (y > 5)
Console.WriteLine("x and y are > 5");
else
Console.WriteLine("x is <= 5");

in which the body of the first if is a nested if…else. The outer if statement tests whether x is
greater than 5. If so, execution continues by testing whether y is also greater than 5. If the second
condition is true, the proper string—"x and y are > 5"—is displayed. However, if the second con-
dition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5.
Equally bad, if the outer if statement’s condition is false, the inner if…else is skipped and
nothing is displayed. For this exercise, add braces to the preceding code snippet to force the nested
if…else statement to execute as it was originally intended.

5.28 (Another Dangling-else Problem) Based on the dangling-else discussion in Exercise 5.27,
state the output for each of the following code snippets when m is 8 and n is 4 and when m is 4 and
n is 8. We eliminated the indentation from the following code to make the problem more challeng-
ing. [Hint: Apply the indentation conventions you’ve learned.]
a) if (m > 5)
if (n < 20)
Console.WriteLine("RGB Mode");
else
Console.WriteLine("CMYK Mode");
Console.WriteLine("GreyScale Mode");
Exercises 229

b) if (m > 5)
if (n < 20)
{
Console.WriteLine("RGB Mode");
}
else
{
Console.WriteLine("CMYK Mode");
Console.WriteLine("GreyScale Mode");
}

5.29 (Another Dangling-else Problem) Based on the dangling-else discussion in Exercise 5.27,
modify the given code to produce the output shown in each part of the problem. Use proper inden-
tation techniques. You must not make any additional changes other than inserting braces. We elim-
inated the indentation from the following code to make the problem more challenging. [Note: It’s
possible that no modification is necessary.]
if (y == 8)
if (x == 5)
Console.WriteLine("@@@@@");
else
Console.WriteLine("#####");
Console.WriteLine("$$$$$");
Console.WriteLine("&&&&&");

a) Assuming that x = 5 and y = 8, the following output is produced:


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

b) Assuming that x = 5 and y = 8, the following output is produced:


@@@@@

c) Assuming that x = 5 and y = 8, the following output is produced:


@@@@@
&&&&&

d) Assuming that x = 5 and y = 7, the following output is produced.


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

5.30 (Rectangle of Asterisks) Write an app that prompts the user to enter the length and width of a
rectangle, then displays a rectangle of that length and width made of and filled with asterisks. Your app
should work for rectangles of all lengths between 1 and 15 and of all widths between 1 and 10. If the user
enters a length or width less than 1 or a length greater than 15 and a width greater than 10, your app
should display a rectangle with either length and width as 1 or length as 15 and width as 10, respectively.
5.31 (Expanded form) A number is in its expanded form when it is expressed as the sum of the
products of its digits and the place value of each digit in the number. For example, 13023 can be
expressed as (1 × 10000) + (3 × 1000) + (0 × 100) + (2 × 10) + (3 × 1). Write an app that reads in
a six-digit integer and shows its expanded form. If the number is not six digits long, display an error
message, and allow the user to enter a new number. [Hint: Use the remainder and division operators
to pick off the number’s digits one at a time, from right to left.]
5.32 (Displaying the Decimal Equivalent of a Binary Number) Write an app that inputs an in-
teger containing only 0s and 1s (i.e., a binary integer) and displays its decimal equivalent. [Hint:
Picking the digits off a binary number is similar to picking the digits off a decimal number, which
230 Chapter 5 Algorithm Development and Control Statements: Part 1

you did in Exercise 5.31. In the decimal number system, the rightmost digit has a positional value
of 1 and the next digit to the left has a positional value of 10, then 100, then 1000 and so on. The
decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system,
the rightmost digit has a positional value of 1, the next digit to the left has a positional value of 2,
then 4, then 8 and so on. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8, or
1 + 0 + 4 + 8, or 13.]
5.33 (Checkerboard Pattern of Asterisks) Write an app that uses only the output statements
Console.Write("* ");
Console.Write(" ");
Console.WriteLine();

to display the checkerboard pattern that follows. A Console.WriteLine method call with no argu-
ments outputs a single newline character. [Hint: Iteration statements are required.]

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

5.34 (Multiples of 2) Write an app that keeps displaying in the console window the powers of
the integer 2—namely, 2, 4, 8, 16, 32, 64 and so on. Loop 40 times. What happens when you run
this app?
5.35 (What’s Wrong with This Code?) What is wrong with the following statement? Provide the
correct statement.
int pr = (--( a * b ));

5.36 (Angles of a Quadrilateral) Write an app that reads four nonzero values entered by the user,
then determines and displays whether they could represent the angles of a quadrilateral.
5.37 (Type of parallelogram) Write an app that reads four nonzero integers, then determines and
displays whether they could represent the sides and diagonals of a square, a rhombus, or a rectangle.
5.38 (Factorials) The factorial of a nonnegative integer n is written as n! (pronounced “n facto-
rial”) and is defined 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. Write an app that reads a nonnegative integer and
computes and displays its factorial.
5.39 (Infinite Series: Mathematical Constant e) Write an app that estimates the value of the
mathematical constant e by using the formula
1 1 1
e = 1 + ----- + ----- + ----- + …
1! 2! 3!
The predefined constant Math.E (class Math is in the System namespace) provides a good approxi-
mation of e. Use the WriteLine method to output both your estimated value of e and Math.E for
comparison.
Making-a-Difference Exercises 231

5.40 (Infinite Series: ex) Write an app that computes the value of e x by using the formula
2 3
x x x x
e = 1 + ----- + ----- + ----- + …
1! 2! 3!

Compare the result of your calculation to the return value of the method call
Math.Pow(Math.E, x)

[Note: The predefined method Math.Pow takes two arguments and raises the first argument to the
power of the second. We discuss Math.Pow in Section 6.6.]

Making-a-Difference Exercises
5.41 (World Population Growth) World population has grown considerably over the centuries.
Continued growth could eventually challenge the limits of breathable air, drinkable water, arable
cropland and other limited resources. There’s evidence that growth has been slowing in recent years
and that world population could peak some time this century, then start to decline.
For this exercise, research world-population-growth issues online. Be sure to investigate various
viewpoints. Get estimates for the current world population and its growth rate (the percentage by
which it is likely to increase this year). Write a program that calculates world population growth
each year for the next 75 years, using the simplifying assumption that the current growth rate will stay
constant. When displaying the results, the first column should display the year from year 1 to year
75. The second column should display the anticipated world population at the end of that year.
The third column should display the numerical increase in the world population that would occur
that year. Using your results, determine the year in which the population would be double what it
is today, if this year’s growth rate were to persist. [Hint: Use double variables because int variables
can store values only up to approximately two billion. Display the double values using the format
F0, which displays the values rounded to the closest whole number—0 means no digits to the right
of the decimal point.]
5.42 (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 app 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 display the encrypted integer. Write a
separate app that inputs an encrypted four-digit integer and decrypts it (by reversing the encryption
scheme) to form the original number. Use the format specifier D4 to display the encrypted value in
case the number starts with a 0. The format specifier D is used to format integer values, and D4 indi-
cates that the value should be formatted with a minimum of four digit positions, possibly with lead-
ing zeros.

You might also like