• Home
  • Textbooks
  • Introduction to Java Programming and Data Structures, Comprehensive Version
  • Loops

Introduction to Java Programming and Data Structures, Comprehensive Version

Daniel Y. Liang

Chapter 5

Loops - all with Video Answers

Educators


Chapter Questions

01:54

Problem 1

Write a program that prompts a student to enter a Java score. If the score is greater or equal to 60 , display "you pass the exam"; otherwise, display "you don't pass the exam". Your program ends with input -1 . Here is a sample run:

Enter your score: $8 0 \longdiv { - \text { -Enter } }$
You pass the exam.
Enter your score: $5 9 \longdiv { - \text { -Enter } }$
You don't pass the exam.

Enter your score: $- 1 \longdiv { - \text { -Enter } }$
No numbers are entered except 0

Alexander Cheng
Alexander Cheng
Numerade Educator
05:12

Problem 2

Listing 5.4, SubtractionQuizLoop.java, generates five random subtraction questions. Revise the program to generate ten random multiplication questions for two integers between 1 and 12. Display the correct count and test time.

Harriet O'Brien
Harriet O'Brien
Numerade Educator
03:37

Problem 3

Write a program that displays the following table (note that farenheit $=$ celsius $* 9 / 5+32$ ):
$$
\begin{array}{lr}
\text { Celsius } & \text { Fahrenheit } \\
0 & 32.0 \\
2 & 35.6 \\
\ldots & \\
98 & 208.4 \\
100 & 212.0
\end{array}
$$

WM
William Mead
Numerade Educator
00:53

Problem 4

Write a program that displays the following table (note that 1 inch is 2.54 centimeters):
$$
\begin{array}{ll}
\text { Inches } & \text { Centimetres } \\
1 & 2.54 \\
2 & 5.08 \\
\ldots & \\
9 & 22.86 \\
10 & 25.4
\end{array}
$$

Willis James
Willis James
Numerade Educator
03:37

Problem 5

Write a program that displays the following two tables side by side:
$$
\begin{array}{lrllr}
\text { Ce1sius } & \text { Fahrenheit } & & \text { Fahrenheit } & \text { Ce1sius } \\
0 & 32.000 & & 20 & -6.667 \\
2 & 35.600 & & 25 & -3.889 \\
\ldots & & & & \\
98 & 208.400 & & 265 & 129.444 \\
100 & 212.000 & & 270 & 132.222
\end{array}
$$

WM
William Mead
Numerade Educator
00:53

Problem 6

Write a program that displays the following two tables side by side (note that 1 ping $=3.305$ square meters):
$$
\begin{array}{lr|lr}
\text { Ping } & \text { Square meter } & \text { Square meter } & \text { Ping } \\
10 & 33.050 & 30 & 9.077 \\
15 & 49.575 & 35 & 10.590 \\
\ldots & & & \\
75 & 247.875 & 95 & 28.744 \\
80 & 264.400 & 100 & 30.257
\end{array}
$$

Willis James
Willis James
Numerade Educator
07:34

Problem 7

Suppose that the tuition for a university is $$\$ 10,000$$ this year and increases $6 \%$ every year. In one year, the tuition will be $$\$ 10,600$$. Write a program that computes the tuition in ten years and the total cost of four years' worth of tuition after the tenth year.

Darren Wilson
Darren Wilson
Numerade Educator
10:06

Problem 8

Write a program that prompts the user to enter the number of students and each student's name and score, and finally displays the name of the student with the highest score. Use the next () method in the Scanner class to read a name, rather than using the nextLine () method.

Darren Wilson
Darren Wilson
Numerade Educator
05:14

Problem 9

Write a program that prompts the user to enter the number of students and each student's name and score, and finally displays the names of the students with the lowest and second-lowest scores.

Darren Wilson
Darren Wilson
Numerade Educator
05:40

Problem 10

Write a program that displays all the numbers from 100 to 1,000 , ten per line, that are divisible by 3 and 4 . Numbers are separated by exactly one space.

Darren Wilson
Darren Wilson
Numerade Educator
06:08

Problem 11

Write a program that displays all the numbers from 100 to 200, ten per line, that are divisible by 3 or 4 , but not both. Numbers are separated by exactly one space.

Darren Wilson
Darren Wilson
Numerade Educator
02:22

Problem 12

Use a whi $1 \mathrm{e}$ loop to find the smallest integer $n$ such that $n^3$ is greater than 12,000 .

Darren Wilson
Darren Wilson
Numerade Educator
02:25

Problem 13

Use a whi $1 \mathrm{e}$ loop to find the largest integer $n$ such that $n^2$ is less than 12,000 .
ections 5.8-5.10

Darren Wilson
Darren Wilson
Numerade Educator

Problem 14

Another solution for Listing 5.9 to find the greatest common divisor of two integers $n 1$ and $n 2$ is as follows: First find $d$ to be the minimum of $n 1$ and $n 2$, then check whether $d, d-1, d-2, \ldots, 2$, or 1 is a divisor for both $\mathrm{n} 1$ and $\mathrm{n} 2$ in this order. The first such common divisor is the greatest common divisor for $\mathrm{n} 1$ and $\mathrm{n} 2$. Write a program that prompts the user to enter two positive integers and displays the gcd.

Check back soon!
04:18

Problem 15

Write a program that prints the characters in the ASCII character table from ! to . Display 10 characters per line. The ASCII table is given in Appendix B. Characters are separated by exactly one space.

Darren Wilson
Darren Wilson
Numerade Educator
05:04

Problem 16

Write a program that reads an integer and displays all its smallest factors in an increasing order. For example, if the input integer is 120 , the output should be as follows: $2,2,2,3,5$.

Darren Wilson
Darren Wilson
Numerade Educator
01:40

Problem 17

Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid, as shown in the following sample run:
Enter the number of 1 ines: 7
$\begin{array}{lllllllllllll}7 & 6 & 5 & 4 & 3 & 2 & 1 & 2 & 3 & 4 & 5 & 6 & 7\end{array}$
$\begin{array}{lllllllll}5 & 4 & 3 & 2 & 1 & 2 & 3 & 4 & 5\end{array}$
$\begin{array}{lllllll}4 & 3 & 2 & 1 & 2 & 3 & 4\end{array}$
$\begin{array}{lllll}3 & 2 & 1 & 2 & 3\end{array}$

Banhishikha Sinha
Banhishikha Sinha
Numerade Educator
02:55

Problem 18

Use nested loops that display the following patterns in four separate programs:
(FIGURE CAN'T COPY)

Caleb Hurlbert
Caleb Hurlbert
Numerade Educator

Problem 19

Write a nested for loop that prints the following output:
(FIGURE CAN'T COPY)

Check back soon!
06:08

Problem 20

Modify Listing 5.15 to display all the prime numbers between 2 and 1,200, inclusive. Display eight prime numbers per line. Numbers are separated by exactly one space.

Darren Wilson
Darren Wilson
Numerade Educator
13:23

Problem 21

Write a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from $5 \%$ to $10 \%$, with an increment of $1 / 4$. Here is a sample run:
Loan Amount: 10000
Number of Years: 5
$$
\begin{array}{lcc}
\text { Interest Rate } & \text { Month1y Payment } & \text { Total Payment } \\
5.000 \% & 188.71 & 11322.74 \\
5.250 \% & 189.86 & 11391.59 \\
5.500 \% & 191.01 & 11460.70 \\
\ldots & & \\
9.750 \% & 211.24 & 12674.55 \\
10.000 \% & 212.47 & 12748.23
\end{array}
$$
For the formula to compute monthly payment, see Listing 2.9 , ComputeLoan.java.

Darren Wilson
Darren Wilson
Numerade Educator
02:10

Problem 22

The monthly payment for a given loan pays the principal and the interest. The monthly interest is computed by multiplying the monthly interest rate and the balance (the remaining principal). The principal paid for the month is therefore the monthly payment minus the monthly interest. Write a program that lets the user enter the loan amount, number of years, and interest rate then displays the amortization schedule for the loan. Here is a sample run:
Loan Amount: 10000
Number of Years: 1
Annual Interest Rate: 7
Monthly Payment: 865.26
Total Payment: 10383.21
$$
\begin{array}{lllr}
\text { Payment\# } & \text { Interest } & \text { Principal } & \text { Balance } \\
1 & 58.33 & 806.93 & 9193.07 \\
2 & 53.62 & 811.64 & 8381.43 \\
\text { i1 } & & & \\
12 & 10.00 & 855.26 & 860.27 \\
12 & 5.01 & 860.25 & 0.01
\end{array}
$$

Ahmad Reda
Ahmad Reda
Numerade Educator
04:37

Problem 23

A cancellation error occurs when you are manipulating a very large number with a very small number. The large number may cancel out the smaller number. For example, the result of 100000000.0 + 0.000000001 is equal to 100000000 . 0 . To avoid cancellation errors and obtain more accurate results, carefully select the order of computation. For example, in computing the following summation, you will obtain more accurate results by computing from right to left rather than from left to right:
$$
1+\frac{1}{2}+\frac{1}{3}+\ldots+\frac{1}{n}
$$

Write a program that compares the results of the summation of the preceding series, computing from left to right and from right to left with $\mathrm{n}=50000$.

Darren Wilson
Darren Wilson
Numerade Educator
02:16

Problem 24

Write a program to compute the following summation:
$$
\frac{1}{3}+\frac{3}{5}+\frac{5}{7}+\frac{7}{9}+\frac{9}{11}+\frac{11}{13}+\cdots+\frac{95}{97}+\frac{97}{99}
$$

Darren Wilson
Darren Wilson
Numerade Educator
05:10

Problem 25

You can approximate $\pi$ by using the following summation:
$$
\pi=4\left(1-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}+\frac{1}{9}-\frac{1}{11}+\cdots+\frac{(-)^{i+1}}{2 i-1}\right)
$$

Write a program that displays the $\pi$ value for $i=10000,20000, \ldots$, and 100000 .

Darren Wilson
Darren Wilson
Numerade Educator
04:18

Problem 26

You can approximate e using the following summation:
$$
e=1+\frac{1}{1 !}+\frac{1}{2 !}+\frac{1}{3 !}+\frac{1}{4 !}+\cdots+\frac{1}{i !}
$$

Write a program that displays the value for $i=10000,20000, \ldots$, and 100000 . (Hint: Because $i !=i \times(i-1) \times \ldots \times 2 \times 1$, then
$$
\frac{1}{i !} \text { is } \frac{1}{i(i-1) !}
$$

Initialize e and item to be 1 , and keep adding a new item to e. The new item is the previous item divided by $i$, for $i>=2$.)

Darren Wilson
Darren Wilson
Numerade Educator
05:30

Problem 27

Write a program that displays all the leap years, ten per line, from 2014 to 2114 , separated by exactly one space. Also display the number of leap years in this period.

Darren Wilson
Darren Wilson
Numerade Educator
01:51

Problem 28

Write a program that prompts the user to enter the year and first day of the year, then displays the first day of each month in the year. For example, if the user entered the year 2013, and 2 for Tuesday, January 1,2013 , your program should display the following output:
January 1, 2013 is Tuesday
...
December 1, 2013 is Sunday

Morgan Cheatham
Morgan Cheatham
Numerade Educator
06:54

Problem 29

Write a program that prompts the user to enter the year and first day of the year and displays the calendar table for the year on the console. For example, if the user entered the year 2013, and 2 for Tuesday, January 1, 2013, your program should display the calendar for each month in the year, as follows:
$$
\begin{array}{rrrrrrr}
\hline \text { Sun } & \text { Mon } & \text { Tue } & \text { Wed } & \text { Thu } & \text { Fri } & \text { Sat } \\
& & 1 & 2 & 3 & 4 & 5 \\
6 & 7 & 8 & 9 & 10 & 11 & 12 \\
13 & 14 & 15 & 16 & 17 & 18 & 19 \\
20 & 21 & 22 & 23 & 24 & 25 & 26 \\
27 & 28 & 29 & 30 & 31 & &
\end{array}
$$

Harriet O'Brien
Harriet O'Brien
Numerade Educator
05:56

Problem 30

Suppose you save $$\$ 100$$ each month in a savings account with annual interest rate $3.75 \%$. The monthly interest rate is $0.0375 / 12=0.003125$. After the first month, the value in the account becomes
$$
100 *(1+0.003125)=100 \cdot 3125
$$

After the second month, the value in the account becomes
$$
100+100.3125) *(1+0.003125)=200.938
$$

After the third month, the value in the account becomes
$$
(100+200.938) *(1+0.003125)=301.878
$$
and so on.
Write a program that prompts the user to enter an amount (e.g., 100), the annual interest rate (e.g., 3.75), and the number of months (e.g., 6) and displays the amount in the savings account after the given month.

Darren Wilson
Darren Wilson
Numerade Educator
08:07

Problem 31

Suppose you put $$\$ 10,000$$ into a CD with an annual percentage yield of $6.15 \%$. After one month, the CD is worth
$$
10000+10000 * 6.15 / 1200=10051.25
$$

After two months, the CD is worth
$$
10051.25+10051.25 * 6.15 / 1200=10102.76
$$

After three months, the CD is worth
$$
10102.76+10102.76 * 6.15 / 1200=10154.53
$$
and so on.
Write a program that prompts the user to enter an amount (e.g., 10000), the annual percentage yield (e.g., 6.15), and the number of months (e.g., 18) and displays a table as shown in the sample run.

Enter the initial deposit amount: 10000 -Enter
Enter annual percentage yield: 6.15 -Enter
Enter maturity period (number of months): $18 \overline{\Delta \text { Eiter }}$
$$
\begin{array}{ll}
\text { Month } & \text { CD Value } \\
1 & 10051.25 \\
2 & 10102.76 \\
\ldots & \\
17 & 10907.90 \\
18 & 10963.81
\end{array}
$$

Ernest Castorena
Ernest Castorena
Numerade Educator
05:19

Problem 32

Revise Listing 3.8, Lottery.java, to generate a lottery of a two-digit number. The two digits in the number are distinct. (Hint: Generate the first digit. Use a loop to continuously generate the second digit until it is different from the first digit.)

Prathan Jarupoonphol
Prathan Jarupoonphol
Numerade Educator
07:24

Problem 33

A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect number because $6=3+2+1$. The next is $28=14+7+4+2+1$. There are four perfect numbers $<10,000$. Write a program to find all these four numbers.

Darren Wilson
Darren Wilson
Numerade Educator
03:28

Problem 34

Programming Exercise 3.17 gives a program that plays the scissor-rock-paper game. Revise the program to let the user continuously play until either the user or the computer wins three times more than their opponent.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
02:45

Problem 35

Write a program to compute the following summation:
$$
\frac{1}{1+\sqrt{2}}+\frac{1}{\sqrt{2}+\sqrt{3}}+\frac{1}{\sqrt{3}+\sqrt{4}}+\ldots+\frac{1}{\sqrt{999}+\sqrt{1000}}
$$

Darren Wilson
Darren Wilson
Numerade Educator

Problem 36

Use loops to simplify Programming Exercise 3.9.

Check back soon!
05:58

Problem 37

Write a program that prompts the user to enter a decimal integer then displays its corresponding binary value. Don't use Java's Integer . toBinaryString (int) in this program.

Darren Wilson
Darren Wilson
Numerade Educator
05:58

Problem 38

Write a program that prompts the user to enter a decimal integer and displays its corresponding octal value. Don't use Java's Integer. to0ctalString(int) in this program.

Darren Wilson
Darren Wilson
Numerade Educator
05:03

Problem 39

You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $$\$ 5,000$$. The scheme shown below is used to determine the commission rate.
$$
\begin{array}{lr}
\text { Sales Amount } & \text { Commission Rate } \\
\hline \$ 0.01-\$ 5,000 & 6 \text { percent } \\
\$ 5,000.01-\$ 10,000 & 8 \text { percent } \\
\$ 10,000.01 \text { and above } & 10 \text { percent }
\end{array}
$$
Note that this is a graduated rate. The rate for the first $$\$ 5,000$$ is at $6 \%$, the next $$\$ 5000$$ is at $8 \%$, and the rest is at $10 \%$. If your sales amounts to $$\$ 25,000$$, the commission is $5,000 * 6 \%+5,000 * 8 \%+15,000 * 10 \%=2,200$. Your goal is to earn $$\$ 30,000$$ a year. Write a program to find the minimum sales you have to generate in order to make $$\$ 30,000$$.

Darren Wilson
Darren Wilson
Numerade Educator
04:23

Problem 40

Write a program that simulates flipping a coin two millions times and displays the number of heads and tails.

Darren Wilson
Darren Wilson
Numerade Educator
04:58

Problem 41

Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume the input ends with number 0. Suppose you entered 35225550 ; the program finds that the largest is 5 and the occurrence count for 5 is 4 .
(Hint: Maintain two variables, max and count. max stores the current max number and count stores its occurrences. Initially, assign the first number to max and 1 to count. Compare each subsequent number with max. If the number is greater than max, assign it to max and reset count to 1 . If the number is equal to max, increment count by 1 .)
The largest number is 5
The occurrence count of the largest number is 4

Darren Wilson
Darren Wilson
Numerade Educator

Problem 42

Rewrite Programming Exercise 5.39 as follows:
- Use a while loop instead of a do-while loop.
- Let the user enter COMMISSION_SOUGHT instead of fixing it as a constant.

Check back soon!
03:51

Problem 43

Write a program that displays all possible combinations for picking two numbers from integers 1 to 7 . Also display the total number of all combinations.
12
13
...
...
The total number of all combinations is 21

Darren Wilson
Darren Wilson
Numerade Educator

Problem 44

A by te value is stored in 8 bits. Write a program that prompts the user to enter a byte integer and displays the 8 bits for the integer. Here are sample runs:
Enter an integer: 5 PEnter
The 8 bits are 00000101
Enter an integer: $- 5 \longdiv { - \text { Enter } }$
The 8 bits are 11111011
(Hint: You need to use the bitwise right shift operator ( $\gg$ ) and the bitwise AND operator (\&), which are covered in Appendix G, Bitwise Operations.)

Check back soon!
03:16

Problem 45

In business applications, you are often asked to compute the mean and standard deviation of data. The mean is simply the average of the numbers. The standard deviation is a statistic that tells you how tightly all the various data are clustered around the mean in a set of data. For example, what is the average age of the students in a class? How close are the ages? If all the students are the same age, the deviation is 0 .
Write a program that prompts the user to enter 10 numbers and displays the mean and standard deviations of these numbers using the following formula:
$$
\text { mean }=\frac{\sum_{i=1}^n x_i}{n}=\frac{x_1+x_2+\cdots+x_n}{n} \text { deviation }=\sqrt{\frac{\sum_{i=1}^n x_i^2-\frac{\left(\sum_{i=1}^n x_i\right)^2}{n}}{n-1}}
$$
Here is a sample run:
The mean is 5.61
The standard deviation is 2.99794

MS
Malcom Smith
Numerade Educator
05:07

Problem 46

Write a program that prompts the user to enter a string and displays the string in reverse order.
Enter a string: $A B C D$ -
The reversed string is DCBA

Brian Ketelobeter
Brian Ketelobeter
Numerade Educator

Problem 47

ISBN - 13 is a new standard for identifying books. It uses 13 digits $d_1 d_2 d_5 d_4 d_5 d_6 d_7 d_8 d_y d_{10} d_{11} d_{12} d_{15}$. The last digit $d_{13}$ is a checksum, which is calculated from the other digits using the following formula:
$$
10-\left(d_1+3 d_2+d_3+3 d_4+d_5+3 d_6+d_7+3 d_8+d_9+3 d_{10}+d_{11}+3 d_{12}\right) \% 10
$$

If the checksum is 10 , replace it with 0 . Your program should read the input as a string. Here are sample runs:

Enter the first 12 digits of an ISBN-13 as a string: 978013213080 The ISBN-13 number is 9780132130806

Enter the first 12 digits of an ISBN-13 as a string: 978013213079 The ISBN-13 number is 9780132130790

Enter the first 12 digits of an ISBN-13 as a string: 97801320
- Enter
97801320 is an invalid input

Check back soon!

Problem 48

Write a program that prompts the user to enter a string and displays the characters at even positions. Here is a sample run:
Enter a string: Beijing Chicago
IEnter
ejnhcg

Check back soon!
03:29

Problem 49

Assume that the letters A, E, I, 0, and U are vowels. Write a program that prompts the user to enter a string, and displays the number of vowels and consonants in the string.
Enter a string: Programming is fun atenter
The number of vowels is 5
The number of consonants is 11

James Kiss
James Kiss
Numerade Educator
00:53

Problem 50

Write a program that uses for, while, and do-while loop statements to display the multiplication table. Here is a sample run:
$$
\begin{aligned}
&\text { Enter a string: Welcome to Java JEnter }\\
&\begin{array}{llllllll}
1 * 1=1 & 2 * 1=2 & 3 * 1=3 & 4 * 1=4 & 5 * 1=5 & 6 * 1=6 & 7 * 1=7 & 8 * 1=8 \\
9 * 1=9 & & & & & & & \\
1 * 2=1 & 2 * 2=2 & 3 * 2=6 & 4^* 2=8 & 5 * 2=10 & 6 * 2=12 & 7 * 2=14 & 8 * 2=16 \\
9 * 2=18 & & & & & & & \\
1 * 3=3 & 2 * 3=6 & 3 * 3=9 & 4 * 3=12 & 5 * 3=15 & 6 * 3=18 & 7 * 3=21 & 8 * 3=24 \\
9 * 3=27 & & & & & & & \\
1 * 4=4 & 2 * 4=8 & 3 * 4=12 & 4 * 4=16 & 5 * 4=20 & 6 * 4=24 & 7 * 4=28 & 8 * 4=32 \\
9 * 4=36 & & & & & & & \\
1 * 5=5 & 2 * 5=10 & 3 * 5=15 & 4 * 5=20 & 5 * 5=25 & 6 * 5=30 & 7 * 5=35 & 8 * 5=40 \\
9 * 5=45 & & & & & & & \\
1 * 6=6 & 2 * 6=12 & 3 * 6=18 & 4 * 6=24 & 5 * 6=30 & 6 * 6=36 & 7 * 6=42 & 8 * 6=48 \\
9 * 6=54 & & & & & & & \\
1 * 7=7 & 2 * 7=14 & 3 * 7=21 & 4 * 7=28 & 5 * 7=35 & 6 * 7=42 & 7 * 7=49 & 8 * 7=56 \\
9 * 7=63 & & & & & & & \\
1 * 8=8 & 2 * 8=16 & 3 * 8=24 & 4 * 8=32 & 5 * 8=40 & 6 * 8=48 & 7 * 8=56 & 8 * 8=64 \\
9 * 8=72 & & & & & & & \\
1 * 9=9 & 2 * 9=18 & 3 * 9=27 & 4 * 9=36 & 5 * 9=45 & 6 * 9=54 & 7 * 9=63 & 8 * 9=72 \\
9 * 9=81 & & & & & & &
\end{array}
\end{aligned}
$$

Willis James
Willis James
Numerade Educator
09:56

Problem 51

Write a program that prompts the user to enter two strings and displays the largest common prefix of the two strings. Here are some sample runs:
Enter the first string: Welcome to C++ -Enter
Enter the second string: Welcome to programming
Enter
The common prefix is Welcome to

Enter the first string: Atlanta
-Enter
Enter the second string: Macon $\Delta$ Enter
Atlanta and Macon have no common prefix

Brian Ketelobeter
Brian Ketelobeter
Numerade Educator