The Outer Loop Will Determine if the User Wants to Play Again (Y or N)
ane.3 Conditionals and Loops
In the programs that nosotros have examined to this signal, each of the statements is executed once, in the guild given. Most programs are more complicated because the sequence of statements and the number of times each is executed tin vary. Nosotros use the term command menses to refer to statement sequencing in a programme.
If statements.
Almost computations crave different actions for different inputs.
- The post-obit code fragment uses an if statement to put the smaller of two int values in 10 and the larger of the two values in y, past exchanging the values in the two variables if necessary.
- Flip.java uses Math.random() and an if-else statement to print the results of a coin flip.
- The table beneath summarizes some typical situations where yous might need to use an if or if-else statement.
While loops.
Many computations are inherently repetitive. The
whileloop enables us to execute a group of statements many times. This enables usa to express lengthy computations without writing lots of lawmaking.
- The following code fragment computes the largest power of 2 that is less than or equal to a given positive integer n.
- TenHellos.java prints "How-do-you-do World" ten times.
- PowersOfTwo.java takes an integer command-line argument n and prints all of the powers of 2 less than or equal to n.
For loops.
The for loop is an alternate Coffee construct that allows us even more flexibility when writing loops.
- For notation. Many loops follow the same basic scheme: initialize an index variable to some value and then use a while loop to test an go out condition involving the index variable, using the terminal argument in the while loop to modify the index variable. Java's for loop is a direct way to express such loops.
- Compound consignment idioms. The idiom i++ is a shorthand annotation for i = i + 1.
- Scope. The telescopic of a variable is the part of the programme that can refer to that variable past name. Generally the telescopic of a variable comprises the statements that follow the declaration in the aforementioned block as the proclamation. For this purpose, the code in the for loop header is considered to be in the same block as the for loop torso.
Nesting.
The
if,
while, and
forstatements have the aforementioned condition as assignment statements or whatsoever other statements in Java; that is, we can use them wherever a argument is called for. In particular, we tin use one or more than of them in the torso of another argument to brand compound statements. To emphasize the nesting, we apply indentation in the program code.
- DivisorPattern.java has a for loop whose trunk contains a for loop (whose trunk is an if-else statement) and a impress argument. It prints a pattern of asterisks where the ith row has an asterisk in each position corresponding to divisors of i (the same holds true for the columns).
- MarginalTaxRate.java computes the marginal revenue enhancement charge per unit for a given income. Information technology uses several nested if-else statements to test from among a number of mutually exclusive possibilities.
Loop examples.
Applications.
The ability to program with loops and conditionals immediately opens upwards the world of ciphering to usa.
- Ruler subdivisions. RulerN.java takes an integer command-line argument n and prints the string of ruler subdivision lengths. This program illustrates one of the essential characteristics of loops—the program could hardly be simpler, but it tin can produce a huge amount of output.
- Finite sums. The computational image used in PowersOfTwo.java is 1 that you will employ frequently. It uses two variables—ane as an index that controls a loop, and the other to accumulate a computational issue. Program HarmonicNumber.java uses the same paradigm to evaluate the sum
$$ H_n = \frac{1}{1} + \frac{1}{2} + \frac{one}{iii} + \frac{1}{4} + \; \ldots \; + \frac{1}{north} $$
These numbers, which are known as the harmonic numbers, arise ofttimes in the analysis of algorithms.
- Newton's method. Sqrt.coffee uses a classic iterative technique known as Newton'south method to compute the square root of a positive number x: Start with an estimate t. If t is equal to 10/t (up to machine precision), then t is equal to a square root of x, so the computation is consummate. If not, refine the judge past replacing t with the average of t and x/t. Each time nosotros perform this update, nosotros get closer to the desired answer.
- Number conversion. Binary.java prints the binary (base 2) representation of the decimal number typed as the command-line statement. It is based on decomposing the number into a sum of powers of two. For example, the binary representation of 106 is 11010102, which is the aforementioned equally saying that 106 = 64 + 32 + viii + 2. To compute the binary representation of n, we consider the powers of 2 less than or equal to north in decreasing order to determine which belong in the binary decomposition (and therefore stand for to a 1 chip in the binary representation).
- Gambler's ruin. Suppose a gambler makes a serial of off-white $1 bets, starting with $50, and keep to play until she either goes bankrupt or has $250. What are the chances that she will become home with $250, and how many bets might she wait to make before winning or losing? Gambler.java is a simulation that can help answer these questions. It takes three control-line arguments, the initial stake ($50), the goal amount ($250), and the number of times we want to simulate the game.
- Prime factorization. Factors.java takes an integer control-line statement n and prints its prime factorization. In dissimilarity to many of the other programs that we have seen (which we could do in a few minutes with a estimator or pencil and newspaper), this computation would not be feasible without a computer.
Other conditional and loop constructs.
To exist complete, nosotros consider 4 more Coffee constructs related to conditionals and loops. They are used much less frequently than the
if,
while, and
forstatements that we've been working with, but it is worthwhile to exist aware of them.
- Break statements. In some situations, we desire to immediate exit a loop without letting it run to completion. Java provides the suspension statement for this purpose. Prime number.java takes an integer control-line argument n and prints true if n is prime, and faux otherwise. There are ii different ways to go out this loop: either the intermission statement is executed (because n is non prime) or the loop-continuation status is non satisfied (because due north is prime number).
Note that the pause argument does not apply to if or if-else statements. In a famous programming issues, the U.Due south. phone network crashed because a programmer intended to employ a break statement to go out a complicated if statement.
- Continue statements. Coffee besides provides a way to skip to the next iteration of a loop: the keep statement. When a continue is executed inside the body of a for loopy, the flow of control transfers directly to the increment statement for the next iteration of the loop.
- Switch statements. The if and if-else statements let 1 or two alternatives. Sometimes, a ciphering naturally suggests more than two mutually exclusive alternatives. Java provides the switch statement for this purpose. NameOfDay.java takes an integer between 0 and 6 as a command-line argument and uses a switch statement to print the corresponding name of the 24-hour interval (Sunday to Sat).
- Practice–while loops. A do-while loop is almost the aforementioned every bit a while loop except that the loop-continuation condition is omitted the first time through the loop. RandomPointInCircle.coffee sets x and y then that (x, y) is randomly distributed inside the circumvolve centered at (0, 0) with radius 1.
With Math.random() we go points that are randomly distributed in the two-by-two square center at (0, 0). We just generate points in this region until nosotros detect one that lies within the unit of measurement disk. We always want to generate at least one betoken so a do-while loop is most advisable. We must declare 10 and y outside the loop since nosotros will desire to access their values afterward the loop terminates.
We don't use the following two flow control statements in this textbook, just include them here for completeness.
- Conditional operator. The conditional operator ?: is a ternary operator (three operands) that enables yous to embed a provisional within an expression. The three operands are separated by the ? and : symbols. If the beginning operand (a boolean expression) is truthful, the result has the value of the 2d expression; otherwise it has the value of the 3rd expression.
int min = (x < y) ? x : y;
- Labeled suspension and continue statements. The break and continue statements utilize to the innermost for or while loop. Sometimes we want to spring out of several levels of nested loops. Coffee provides the labeled break and labeled continue statements to accomplish this. Here is an example.
Exercises
- Write a programme AllEqual.java that takes three integer command-line arguments and prints equal if all 3 are equal, and not equal otherwise.
- Write a program RollLoadedDie.java that prints the upshot of rolling a loaded die such that the probability of getting a one, 2, iii, 4, or 5 is 1/8 and the probability of getting a 6 is iii/8.
- Rewrite TenHellos.coffee to make a programme Hellos.java that takes the number of lines to print as a control-line argument. You may presume that the argument is less than 1000. Hint: consider using i % 10 and i % 100 to decide whether to use "st", "nd", "rd", or "th" for printing the ith Hello.
- Write a program FivePerLine.java that, using one for loop and ane if statement, prints the integers from chiliad to 2000 with five integers per line. Hint: utilise the % operator.
- Write a program FunctionGrowth.coffee that prints a table of the values of ln northward, north, n ln north, n2 , north3 , and 2n for due north = xvi, 32, 64, ..., 2048. Use tabs ('\t' characters) to line up columns.
- What is the value of m and northward subsequently executing the following code?
int n = 123456789; int g = 0; while (n != 0) { chiliad = (10 * m) + (northward % 10); n = n / 10; }
- What does the post-obit code print out?
int f = 0, one thousand = 1; for (int i = 0; i <= 15; i++) { System.out.println(f); f = f + 1000; yard = f - g; }
- Dissimilar the harmonic numbers, the sum 1/one + 1/4 + one/9 + 1/16 + ... + 1/n2 does converge to a constant as due north grows to infinity. (Indeed, the constant is π2 / half-dozen, so this formula tin be used to approximate the value of π.) Which of the following for loops computes this sum? Assume that northward is an int initialized to 1000000 and sum is a double initialized to 0.
(a) for (int i = i; i <= n; i++) sum = sum + 1 / (i * i); (b) for (int i = 1; i <= n; i++) sum = sum + 1.0 / i * i; (c) for (int i = 1; i <= n; i++) sum = sum + ane.0 / (i * i); (d) for (int i = ane; i <= n; i++) sum = sum + i / (1.0 * i * i);
- Modify Binary.java to get a program Modify Kary.java that takes a 2d control-line argument K and converts the commencement statement to base of operations 1000. Assume the base is between 2 and 16. For bases greater than 10, use the messages A through F to represent the 11th through 16th digits, respectively.
- Write a program code fragment that puts the binary representation of a positive integer n into a Cord variable s.
Creative Exercises
- Ramanujan'southward taxi. S. Ramanujan was an Indian mathematician who became famous for his intuition for numbers. When the English mathematician K. H. Hardy came to visit him in the hospital ane twenty-four hours, Hardy remarked that the number of his taxi was 1729, a rather tiresome number. To which Ramanujan replied, "No, Hardy! No, Hardy! Information technology is a very interesting number. Information technology is the smallest number expressible equally the sum of 2 cubes in ii different means." Verify this claim by writing a plan Ramanujan.java that takes an integer control-line argument n and prints all integers less than or equal to north that tin can exist expressed as the sum of two cubes in 2 different ways - notice singled-out positive integers a, b, c, and d such that a3 + b3 = c3 + d3 . Utilise four nested for loops.
At present, the license plate 87539319 seems similar a rather dull number. Determine why information technology'south not.
- Checksums. The International Standard Book Number (ISBN) is a 10 digit code that uniquely specifies a book. The rightmost digit is a checksum digit which can be uniquely determined from the other 9 digits from the condition that dane + 2nd2 + 3d3 + ... + 10d10 must be a multiple of 11 (hither di denotes the ith digit from the correct). The checksum digit d1 can exist any value from 0 to 10: the ISBN convention is to use the value Ten to denote 10. Example: the checksum digit corresponding to 020131452 is five since is the merely value of dane between 0 and and x for which d1 + ii*ii + 3*5 + 4*4 + five*1 + 6*3 + 7*i + 8*0 + 9*2 + x*0 is a multiple of eleven. Write a program ISBN.java that takes a 9-digit integer every bit a command-line argument, computes the checksum, and prints the ten-digit ISBN number. It'southward ok if y'all don't print any leading 0s.
- Exponential function. Assume that x is a positive variable of blazon double. Write a program Exp.java that computes e^x using the Taylor series expansion
$$ e^ x = i + ten + \frac{ten^2}{ii!} + \frac{10^3}{3!} + \frac{x^4}{4!} + \ldots $$
- Trigonometric functions. Write two programs Sin.coffee and Cos.java that compute sin x and cos ten using the Taylor series expansions
$$ \sin x = ten - \frac{10^three}{3!} + \frac{ten^5}{5!} - \frac{10^7}{7!} + \ldots $$
$$ \cos 10 = ane - \frac{x^ii}{2!} + \frac{10^4}{four!} - \frac{x^vi}{6!} + \ldots $$
- Game simulation. In the game show Let's Brand a Bargain, a contestant is presented with three doors. Behind one door is a valuable prize, behind the other two are gag gifts. After the contestant chooses a door, the host opens up ane of the other two doors (never revealing the prize, of grade). The contestant is so given the opportunity to switch to the other unopened door. Should the contestant exercise then? Intuitively, it might seem that the contestant'southward initial choice door and the other unopened door are as likely to incorporate the prize, and so there would be no incentive to switch. Write a program MonteHall.coffee to examination this intuition past simulation. Your program should accept an integer control-line argument n, play the game n times using each of the two strategies (switch or don't switch) and impress the chance of success for each strategy. Or you can play the game hither.
- Euler's sum-of-powers theorize. In 1769 Leonhard Euler formulated a generalized version of Fermat'southward Final Theorem, conjecturing that at to the lowest degree n northth powers are needed to obtain a sum that is itself an nth power, for n > ii. Write a program Euler.coffee to disprove Euler's conjecture (which stood until 1967), using a quintuply nested loop to find iv positive integers whose fifth ability sums to the 5th power of another positive integer. That is, discover a, b, c, d, and e such that a 5 + b 5 + c five + d five = due east 5. Apply the long information type.
Web Exercises
- Write a program RollDie.java that generates the event of rolling a off-white half-dozen-sided die (an integer between ane and 6).
- Write a program that takes three integer command-line arguments a, b, and c and print the number of distinct values (1, ii, or 3) among a, b, and c.
- Write a program that takes five integer command-line arguments and prints the median (the third largest one).
- (hard) Now, attempt to compute the median of 5 elements such that when executed, it never makes more than six total comparisons.
- How can I create in an space loop with a for loop?
Solution: for(;;) is the same every bit while(true).
- What's wrong with the following loop?
boolean done = false; while (done = false) { ... }
boolean washed = imitation; while (!done) { ... }
- What's incorrect with the following loop that is intended to compute the sum of the integers 1 through 100?
for (int i = i; i <= North; i++) { int sum = 0; sum = sum + i; } Arrangement.out.println(sum);
- Write a program Hurricane.coffee that that takes the wind speed (in miles per hr) as an integer command-line argument and prints whether it qualifies as a hurricane, and if so, whether it is a Category 1, 2, 3, four, or v hurricane. Beneath is a table of the wind speeds co-ordinate to the Saffir-Simpson scale.
Category Wind Speed (mph) one 74 - 95 2 96 - 110 3 111 - 130 4 131 - 155 5 155 and in a higher place - What is incorrect with the following code fragment?
double x = -32.2; boolean isPositive = (10 > 0); if (isPositive = true) System.out.println(x + " is positive"); else System.out.println(x + " is not positive");
Solution: It uses the assignment operator = instead of the equality operator ==. A better solution is to write if (isPositive).
- Modify/add i graphic symbol and then that the following program prints twenty xs. There are two different solutions.
int i = 0, north = 20; for (i = 0; i < n; i--) System.out.print("x");
- What does the following code fragment exercise?
if (ten > 0); System.out.println("positive");
Solution: always prints positive regardless of the value of x because of the actress semicolon after the if argument.
- RGB to HSB converter. Write a program RGBtoHSV.java that takes an RGB colour (three integers betwixt 0 and 255) and transforms it to an HSB color (three different integers between 0 and 255). Write a program HSVtoRGB.java that applies the inverse transformation.
- Boys and girls. A couple beginning a family decides to go along having children until they have at to the lowest degree 1 of either sex. Guess the average number of children they will have via simulation. Also judge the most common result (record the frequency counts for two, 3, and 4 children, and also for 5 and above). Assume that the probability p of having a male child or girl is i/2.
- What does the following plan do?
public static void master(String[] args) { int N = Integer.parseInt(args[0]); int x = 1; while (Northward >= i) { Organization.out.println(10); 10 = 2 * 10; N = Northward / two; } }
- Boys and girls. Echo the previous question, but presume the couple keeps having children until they have another child which is of the same sex activity every bit the commencement kid. How does your answer change if p is unlike from 1/2?
Surprisingly, the average number of children is two if p = 0 or one, and 3 for all other values of p. But the nigh probable value is 2 for all values of p.
- Given 2 positive integers a and b, what event does the post-obit code fragment leave in c
c = 0; while (b > 0) { if (b % 2 == 1) c = c + a; b = b / 2; a = a + a; }
Solution: a * b.
- Write a program using a loop and 4 conditionals to print
12 midnight 1am 2am ... 12 apex 1pm ... 11pm
- What does the following program print?
public class Examination { public static void main(Cord[] args) { if (x > 5); else; { System.out.println("Here"); }; } }
- Alice tosses a off-white coin until she sees 2 consecutive heads. Bob tosses some other fair coin until he sees a head followed by a tail. Write a plan to estimate the probability that Alice will brand fewer tosses than Bob? Solution: 39/121.
- Rewrite DayOfWeek.coffee from Do 1.2.29 so that it prints the 24-hour interval of the week every bit Sunday, Monday, and so along instead of an integer betwixt 0 and 6. Utilize a switch statement.
- Number-to-English. Write a program to read in a command line integer betwixt -999,999,999 and 999,999,999 and impress the English equivalent. Here is an exhaustive list of words that your program should use: negative, zip, 1, two, three, iv, five, half dozen, seven, 8, 9, 10, xi, twelve, thirteen, fourteen, 15, sixteen, seventeen, eighteen, nineteen, twenty, thirty, forty, 50, sixty, seventy, fourscore, ninety, hundred, thousand, million . Don't apply hundred, when you can apply thousand, eastward.k., apply one thousand five hundred instead of fifteen hundred. Reference.
- Gymnastics judging. A gymnast's score is adamant by a panel of 6 judges who each decide a score between 0.0 and ten.0. The final score is determined by discarding the high and depression scores, and averaging the remaining 4. Write a program GymnasticsScorer.java that takes 6 real command line inputs representing the 6 scores and prints their average, afterwards throwing out the loftier and low scores.
- Quarterback rating. To compare NFL quarterbacks, the NFL devised a the quarterback rating formula based on the quarterbacks number of completed passes (A), pass attempts (B), passing yards (C), touchdown passes (D), and interception (E) as follows:
- Completion ratio: West = 250/3 * ((A / B) - 0.3).
- Yards per pass: 10 = 25/vi * ((C / B) - 3).
- Touchdown ratio: Y = 1000/3 * (D / B)
- Interception ratio: Z = 1250/3 * (0.095 - (Due east / B))
- Decimal expansion of rational numbers. Given 2 integers p and q, the decimal expansion of p/q has an infinitely repeating bike. For example, 1/33 = 0.03030303.... We use the annotation 0.(03) to announce that 03 repeats indefinitely. As another example, 8639/70000 = 0.1234(142857). Write a program DecimalExpansion.java that reads in 2 command line integers p and q and prints the decimal expansion of p/q using the above notation. Hint: employ Floyd's rule.
- Fri the 13th. What is the maximum number of sequent days in which no Friday the 13th occurs? Hint: The Gregorian calendar repeats itself every 400 years (146097 days) and so y'all only need to worry almost a 400 year interval.
Solution: 426 (east.grand., from viii/13/1999 to 10/xiii/2000).
- January ane. Is January 1 more likely to fall on a Saturday or Sunday? Write a program to determine the number of times each occurs in a 400 year interval.
Solution: Sunday (58 times) is more likely than Saturday (56 times).
- What practise the following two code fragments practice?
for (int i = 0; i < Due north; i++) for (int j = 0; j < Due north; j++) if (i != j) Arrangement.out.println(i + ", " + j); for (int i = 0; i < N; i++) for (int j = 0; (i != j) && (j < Due north); j++) System.out.println(i + ", " + j);
- Determine what value gets printed out without using a computer. Cull the correct answer from 0, 100, 101, 517, or 1000.
int cnt = 0; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) for (int thou = 0; chiliad < ten; k++) if (2*i + j >= three*k) cnt++; System.out.println(cnt);
- Rewrite CarLoan.coffee from Creative Practise XYZ so that it properly handles an interest charge per unit of 0% and avoids dividing by 0.
- Write the shortest Java program you tin can that takes an integer command-line argument n and prints true if (one + 2 + ... + n) 2 is equal to (1iii + 23 + ... + niii).
Solution: E'er impress true.
- Alter Sqrt.coffee and then that information technology reports an error if the user enters a negative number and works properly if the user enters null.
- What happens if we initialize t to -x instead of x in program Sqrt.java?
- Sample standard departure of uniform distribution. Change Exercise 8 and so that it prints the sample standard deviation in addition to the boilerplate.
- Sample standard difference of normal distribution. that takes an integer Northward as a command-line statement and uses Web Exercise 1 from Section 1.2 to print N standard normal random variables, and their average value, and sample standard deviation.
- Loaded dice. [Stephen Rudich] Suppose you take 3, 3 sided dice. A: {2, half-dozen, 7}, B: { ane, 5, 9}, and C: {3, 4, 8}. Two players roll a die and the 1 with the highest value wins. Which die would yous choose? Solution: A beats B with probability five/ix, B beats C with probability 5/nine and C beats A with probability 5/9. Be sure to choose second!
- Thue–Morse sequence. Write a program ThueMorse.java that reads in a command line integer n and prints the Thue–Morse sequence of order n. The first few strings are 0, 01, 0110, 01101001. Each successive string is obtained past flipping all of the bits of the previous cord and concatenating the outcome to the end of the previous string. The sequence has many amazing properties. For case, it is a binary sequence that is cube-free: it does not incorporate 000, 111, 010101, or sss where south is whatever cord. It is self-similar: if you lot delete every other flake, you get another Thue–Morse sequence. It arises in diverse areas of mathematics as well as chess, graphic pattern, weaving patterns, and music composition.
- Program Binary.coffee prints the binary representation of a decimal number n by casting out powers of ii. Write an alternate version Plan Binary2.coffee that is based on the following method: Write 1 if n is odd, 0 if n is fifty-fifty. Divide n past 2, throwing away the remainder. Echo until n = 0 and read the answer backwards. Utilize % to determine whether northward is even, and utilise string chain to class the respond in reverse guild.
- What does the following code fragment do?
int digits = 0; practice { digits++; northward = n / 10; } while (n > 0);
Solution: The number of $.25 in the binary representation of a natural number n. We employ a practice-while loop so that code output 1 if north = 0.
- Write a program NPerLine.java that takes an integer command-line argument n and prints the integers from 10 to 99 with n integers per line.
- Modify NPerLine.java so that it prints the integers from ane to g with n integers per line. Make the integers line up by printing the right number of spaces before an integer (e.g., 3 for 1-9, two for x-99, and 1 for 100-999).
- Suppose a, b, and c are random number uniformly distributed between 0 and i. What is the probability that a, b, and c class the side length of some triangle? Hint: they volition form a triangle if and only if the sum of every two values is larger than the third.
- Echo the previous question, but calculate the probability that the resulting triangle is obtuse, given that the three numbers for a triangle. Hint: the three lengths will class an obtuse triangle if and only if (i) the sum of every 2 values is larger than the 3rd and (ii) the sum of the squares of every two side lengths is greater than or equal to the square of the third.
Answer.
- What is the value of s after executing the following code?
int One thousand = 987654321; String due south = ""; while (M != 0) { int digit = Chiliad % 10; s = s + digit; M = Chiliad / 10; }
- What is the value of i after the following confusing code is executed?
int i = 10; i = i++; i = ++i; i = i++ + ++i;
Moral: don't write code like this.
- Formatted ISBN number. Write a programme ISBN2.java that reads in a 9 digit integer from a command-line statement, computes the check digit, and prints the fully formatted ISBN number, e.g, 0-201-31452-5.
- UPC codes. The Universal Product Lawmaking (UPC) is a 12 digit code that uniquely specifies a product. The least significant digit done(rightmost one) is a bank check digit which is the uniquely determined past making the following expression a multiple of 10:
(d1 + diii + dv + dvii + d9 + d11) + iii (dii + d4 + dhalf-dozen + d8 + d10 + d12)
As an instance, the cheque digit corresponding to 0-48500-00102 (Tropicana Pure Premium Orange Juice) is 8 since
(8 + 0 + 0 + 0 + five + four) + 3 (two + one + 0 + 0 + 8 + 0) = 50
and fifty is a multiple of 10. Write a program that reads in a 11 digit integer from a control line parameter, computes the check digit, and prints the the full UPC. Hint: apply a variable of type long to store the 11 digit number.
- Write a program that reads in the wind speed (in knots) equally a command line statement and prints its strength according to the Beaufort calibration. Utilise a switch argument.
- Making change. Write a plan that reads in a command line integer N (number of pennies) and prints the all-time mode (fewest number of coins) to make modify using The states coins (quarters, dimes, nickels, and pennies but). For example, if N = 73 then print
2 quarters 2 dimes 3 pennies
Hint: use the greedy algorithm. That is, dispense as many quarters as possible, and then dimes, then nickels, and finally pennies.
- Write a programme Triangle.java that takes a control-line argument N and prints an N-past-Northward triangular pattern similar the i below.
* * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *
- Write a program Ex.java that takes a command-line statement N and prints a (2N + 1)-by-(2N + one) ex similar the one beneath. Use two for loops and i if-else statement.
* . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *
- Write a plan BowTie.java that takes a control-line argument Northward and prints a (2N + 1)-by-(2N + i) bowtie similar the 1 below. Use two for loops and i if-else statement.
* . . . . . * * * . . . * * * * * . * * * * * * * * * * * * * . * * * * * . . . * * * . . . . . *
- Write a program Diamond.coffee that takes a control-line argument N and prints a (2N + 1)-by-(2N + 1) diamond like the one below.
% java Diamond iv . . . . * . . . . . . . * * * . . . . . * * * * * . . . * * * * * * * . * * * * * * * * * . * * * * * * * . . . * * * * * . . . . . * * * . . . . . . . * . . . .
- Write a programme Centre.java that takes a command-line argument Northward and prints a heart.
- What does the program Circle.java impress out when N = v?
for (int i = -N; i <= Due north; i++) { for (int j = -N; j <= N; j++) { if (i*i + j*j <= N*Northward) Organization.out.print("* "); else Arrangement.out.print(". "); } System.out.println(); }
- Seasons. Write a program Season.coffee that takes 2 command line integers M and D and prints the season corresponding to calendar month M (1 = January, 12 = December) and day D in the northern hemisphere. Employ the following table
SEASON FROM TO Spring March 21 June twenty Summer June 21 September 22 Fall September 23 December 21 Winter December 21 March twenty - Zodiac signs. Write a program Zodiac.java that takes ii command line integers Thou and D and prints the Zodiac sign respective to calendar month M (i = January, 12 = December) and day D. Apply the following table
SIGN FROM TO Capricorn December 22 January xix Aquarius January 20 February 17 Pisces February 18 March nineteen Aries March 20 Apr 19 Taurus April 20 May 20 Gemini May 21 June 20 Cancer June 21 July 22 Leo July 23 August 22 Virgo August 23 September 22 Libra September 23 Oct 22 Scorpio October 23 November 21 Sagittarius November 22 December 21 - Muay Thai kickboxing. Write a program that reads in the weight of a Muay Thai kickboxer (in pounds) equally a control-line argument and prints their weight class. Use a switch argument.
CLASS FROM TO Flyweight 0 112 Super flyweight 112 115 Bantamweight 115 118 Super bantamweight 118 122 Featherweight 122 126 Super featherweight 126 130 Lightweight 130 135 Super lightweight 135 140 Welterweight 140 147 Super welterweight 147 154 Middleweight 154 160 Super middleweight 160 167 Light heavyweight 167 175 Super light heavyweight 175 183 Cruiserweight 183 190 Heavyweight 190 220 Super heavyweight 220 - - Euler's sum of powers theorize. In 1769 Euler generalized Fermat's Concluding Theorem and conjectured that it is impossible to observe three quaternary powers whose sum is a 4th power, or iv 5th powers whose sum is a 5th power, etc. The conjecture was disproved in 1966 by exhaustive computer search. Disprove the theorize by finding positive integers a, b, c, d, and east such that a5 + b5 + c5 + d5= eastward5. Write a programme Euler.coffee that reads in a control line parameter Northward and exhaustively searches for all such solutions with a, b, c, d, and due east less than or equal to N. No counterexamples are known for powers greater than 5, simply y'all can join EulerNet, a distributed calculating effort to find a counterexample for sixth powers.
- Blackjack. Write a plan Blackjack.java that takes iii command line integers x, y, and z representing your two blackjack cards x and y, and the dealers face-upwardly carte du jour z, and prints the "standard strategy" for a six card deck in Atlantic city. Assume that ten, y, and z are integers between i and ten, representing an ace through a face card. Report whether the histrion should hit, stand, or split according to these strategy tables. (When you learn about arrays, you will run across an alternating strategy that does not involve as many if-else statements).
- Blackjack with doubling. Modify the previous practice to allow doubling.
- Projectile motion. The following equation gives the trajectory of a ballistic missile as a function of the initial angle theta and windspeed: xxxx. Write a java program to print the (x, y) position of the missile at each time pace t. Employ trial and error to determine at what angle you should aim the missile if you hope to incinerate a target located 100 miles due east of your current location and at the same elevation. Assume the windspeed is 20 mph due e.
- Globe series. The baseball world series is a best of seven competition, where the first team to win 4 games wins the World Series. Suppose the stronger team has probability p > 1/ii of winning each game. Write a plan to estimate the gamble that the weaker teams wins the World Series and to estimate how many games on average it volition take.
- Consider the equation (9/four)^x = ten^(9/4). One solution is 9/4. Can you lot notice another i using Newton'southward method?
- Sorting networks. Write a program Sort3.coffee with three if statements (and no loops) that reads in three integers a, b, and c from the control line and prints them out in ascending order.
if (a > b) bandy a and b if (a > c) swap a and c if (b > c) swap b and c
- Oblivious sorting network. Convince yourself that the post-obit lawmaking fragment rearranges the integers stored in the variables A, B, C, and D and so that A <= B <= C <= D.
if (A > B) { t = A; A = B; B = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (D > East) { t = D; D = Due east; E = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; }
- Optimal oblivious sorting networks. Create a program that sorts iv integers using simply 5 if statements, and 1 that sorts 5 integers using just 9 if statements of the blazon in a higher place? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How can you check that your program works for all inputs?
Solution: Sort4.java sorts 4 elements using 5 compare-exchanges. Sort5.java sorts 5 elements using 9 compare-exchanges.
The 0-1 principle asserts that you can verify the correctness of a (deterministic) sorting algorithm by checking whether it correctly sorts an input that is a sequence of 0s and 1s. Thus, to bank check that Sort5.java works, you only need to test it on the two^five = 32 possible inputs of 0s and 1s.
- Optimal oblivious sorting (challenging). Discover an optimal sorting network for six, 7, and eight inputs, using 12, 16, and 19 if statements of the form in the previous trouble, respectively.
Solution: Sort6.coffee is the solution for sorting half-dozen elements.
- Optimal non-oblivious sorting. Write a plan that sorts v inputs using only 7 comparisons. Hint: First compare the showtime two numbers, the second ii numbers, and the larger of the 2 groups, and characterization them so that a < b < d and c < d. Second, insert the remaining element e into its proper place in the chain a < b < d by showtime comparison confronting b, then either a or d depending on the outcome. Third, insert c into the proper place in the chain involving a, b, d, and e in the same manner that yous inserted east (with the knowledge that c < d). This uses 3 (first pace) + two (second step) + 2 (3rd footstep) = 7 comparisons. This method was offset discovered past H. B. Demuth in 1956.
- Weather balloon. (Etter and Ingber, p. 123) Suppose that h(t) = 0.12tiv + 12t3 - 380ttwo + 4100t + 220 represents the height of a conditions balloon at time t (measured in hours) for the first 48 hours after its launch. Create a table of the height at time t for t = 0 to 48. What is its maximum peak? Solution: t = 5.
- Volition the post-obit lawmaking fragment compile? If and so, what volition it practise?
int a = ten, b = 18; if (a = b) System.out.println("equal"); else System.out.println("non equal");
Solution: It uses the assignment operator = instead of the equality operator == in the conditional. In Coffee, the effect of this statement is an integer, but the compiler expects a boolean. As a result, the plan will non compile. In some languages (notably C and C++), this code fragment volition gear up the variable a to xviii and print equal without an error.
- Gotcha 1. What does the following code fragment practise?
boolean a = false; if (a = true) Organisation.out.println("yes"); else System.out.println("no");
- Gotcha 2. What does the following code fragment do?
int a = 17, x = 5, y = 12; if (ten > y); { a = xiii; x = 23; } System.out.println(a);
- Gotcha three. What does the following lawmaking fragment do?
for (int x = 0; x < 100; x += 0.5) { Organisation.out.println(10); }
0
. The chemical compound assignment argument10 += 0.5
is equivalent tox = (int) (x + 0.5)
. - What does the post-obit code fragment exercise?
int income = Integer.parseInt(args[0]); if (income >= 311950) rate = .35; if (income >= 174700) rate = .33; if (income >= 114650) charge per unit = .28; if (income >= 47450) rate = .25; if (income >= 0) charge per unit = .22; System.out.println(rate);
- Application of Newton'southward method. Write a program BohrRadius.java that finds the radii where the probability of finding the electron in the 4s excited country of hydrogen is cipher. The probability is given by: (1 - 3r/4 + r2/8 - r3/192)ii e-r/ii , where r is the radius in units of the Bohr radius (0.529173E-8 cm). Use Newton'southward method. Past starting Newton'southward method at different values of r, you lot can discover all three roots. Hint: use initial values of r= 0, five, and 13. Challenge: explicate what happens if yous use an initial value of r = iv or 12.
- Pepys problem. In 1693, Samuel Pepys asked Isaac Newton which was more likely: getting at least i 1 when rolling a fair die 6 times or getting at to the lowest degree 2 1'due south when rolling a off-white dice 12 times. Write a programme Pepys.java that uses simulation to decide the correct respond.
- What is the value of the variable south subsequently running the following loop when N = 1, 2, 3, 4, and v.
String southward = ""; for (int i = i; i <= Due north; i++) { if (i % two == 0) southward = southward + i + s; else s = i + s + i; }
Solution: Palindrome.java.
- Body mass alphabetize. The torso mass alphabetize (BMI) is the ratio of the weight of a person (in kilograms) to the square of the peak (in meters). Write a plan BMI.java that takes ii control-line arguments, weight and height, computes the BMI, and prints the corresponding BMI category:
- Starvation: less than 15
- Anorexic: less than 17.5
- Underweight: less than 18.5
- Platonic: greater than or equal to eighteen.v but less than 25
- Overweight: greater than or equal to 25 merely less than 30
- Obese: greater than or equal to 30 just less than 40
- Morbidly Obese: greater than or equal to xl
- Reynolds number. The Reynolds number is the ratio if inertial forces to sticky forces and is an important quantity in fluid dynamics. Write a plan that takes in 4 command-line arguments, the diameter d, the velocity 5, the density rho, and the viscosity mu, and prints the Reynold's number d * 5 * rho / mu (bold all arguments are in SI units). If the Reynold's number is less than 2000, impress laminar flow, if information technology's between 2000 and 4000, impress transient flow, and if it'southward more than 4000, print turbulent flow.
- Wind chill revisited. The wind chill formula from Exercise 1.two.14 is only valid if the wind speed is to a higher place 3MPH and below 110MPH and the temperature is below l degrees Fahrenheit and above -50 degrees. Change your solution to print an mistake message if the user types in a value outside the allowable range.
- Point on a sphere. Write a program to impress the (x, y, z) coordinates of a random point on the surface of a sphere. Use Marsaglia' method: pick a random point (a, b) in the unit circumvolve as in the do-while case. And then, set up x = 2a sqrt(1 - a^2 - b^2), y = 2b sqrt(1 - a^two - b^2), z = 1 - ii(a^2 + b^two).
- Powers of k. Write a program PowersOfK.java that takes an integer K as command-line argument and prints all the positive powers of K in the Coffee long data type. Annotation: the constant Long.MAX_VALUE is the value of the largest integer in long.
- Square root, revisited. Why not use the loop-continuation condition (Math.abs(t*t - c) > EPSILON) in Sqrt.java instead of Math.abs(t - c/t) > t*EPSILON)?
Solution: Surprisingly, it can lead to inaccurate results or worse. For example, if you supply SqrtBug.java with the control-line argument 1e-50, yous get 1e-l equally the answer (instead of 1e-25); if you supply 16664444, you get an space loop!
- What happens when you attempt to compile the following lawmaking fragment?
double x; if (a >= 0) ten = 3.xiv; if (a < 0) x = 2.71; System.out.println(x);
Solution: It complains that the variable x might non accept been initialized (even though nosotros tin clearly see that x will be initialized past 1 of the ii if statements). You can avoid this problem here by using if-else.
Source: https://introcs.cs.princeton.edu/13flow
0 Response to "The Outer Loop Will Determine if the User Wants to Play Again (Y or N)"
Post a Comment