Write a Loop That Reads Positive Integers From Standard Input and That Terminates

1.3   Conditionals and Loops

In the programs that nosotros have examined to this indicate, each of the statements is executed once, in the order given. Most programs are more complicated considering the sequence of statements and the number of times each is executed tin vary. We apply the term command flow to refer to statement sequencing in a program.

If statements.

Nigh computations require different actions for different inputs.

  • The post-obit lawmaking fragment uses an if argument to put the smaller of ii int values in x and the larger of the 2 values in y, past exchanging the values in the two variables if necessary.
    anatomy of an if statement
  • Flip.java uses Math.random() and an if-else argument to print the results of a coin flip.
  • The table below summarizes some typical situations where you might need to use an if or if-else statement.
    examples of conditionals

While loops.

Many computations are inherently repetitive. The

while

loop enables usa to execute a grouping of statements many times. This enables us to limited lengthy computations without writing lots of lawmaking.

  • The following code fragment computes the largest power of ii that is less than or equal to a given positive integer n.
    anatomy of a while loop
  • TenHellos.java prints "Hello World" x times.
  • PowersOfTwo.java takes an integer command-line statement n and prints all of the powers of 2 less than or equal to north.

For loops.

The for loop is an alternate Java construct that allows united states of america even more flexibility when writing loops.

  • For annotation. Many loops follow the same bones scheme: initialize an index variable to some value and so utilize a while loop to test an get out condition involving the index variable, using the last statement in the while loop to modify the index variable. Coffee'due south for loop is a directly manner to limited such loops.
    anatomy of a for loop
  • Compound consignment idioms. The idiom i++ is a shorthand note for i = i + 1.
  • Scope. The telescopic of a variable is the part of the programme that can refer to that variable by name. More often than not the scope of a variable comprises the statements that follow the proclamation in the same cake as the declaration. For this purpose, the code in the for loop header is considered to be in the same block as the for loop trunk.

Nesting.

The

if

,

while

, and

for

statements have the same status as consignment statements or any other statements in Coffee; that is, we can use them wherever a statement is chosen for. In detail, we can apply 1 or more of them in the body of another argument to make chemical compound statements. To emphasize the nesting, we use indentation in the programme code.

  • DivisorPattern.java has a for loop whose body contains a for loop (whose torso is an if-else statement) and a print argument. It prints a pattern of asterisks where the ithursday row has an asterisk in each position corresponding to divisors of i (the same holds true for the columns).
  • MarginalTaxRate.java computes the marginal taxation rate for a given income. Information technology uses several nested if-else statements to test from among a number of mutually exclusive possibilities.

Loop examples.

examples of loops

Applications.

The ability to program with loops and conditionals immediately opens up the earth of ciphering to us.

  • 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, only it tin can produce a huge amount of output.
  • Harmonic numbers
  • Finite sums. The computational prototype used in PowersOfTwo.java is one that you will employ frequently. Information technology uses two variables—one every bit an alphabetize that controls a loop, and the other to accrue a computational upshot. Program HarmonicNumber.coffee uses the same paradigm to evaluate the sum
    $$ H_n = \frac{i}{1} + \frac{1}{two} + \frac{1}{3} + \frac{1}{4} + \; \ldots \; + \frac{1}{north} $$

    These numbers, which are known equally the harmonic numbers, ascend frequently in the analysis of algorithms.

  • Newton'due south method. Newton's method Sqrt.java uses a classic iterative technique known equally Newton's method to compute the foursquare root of a positive number x: Start with an estimate t. If t is equal to x/t (up to motorcar precision), then t is equal to a foursquare root of ten, so the computation is complete. If not, refine the judge by replacing t with the average of t and ten/t. Each time nosotros perform this update, we get closer to the desired answer.
  • Number conversion. Binary.java prints the binary (base two) representation of the decimal number typed equally the command-line statement. It is based on decomposing the number into a sum of powers of 2. For example, the binary representation of 106 is 11010102, which is the same as saying that 106 = 64 + 32 + 8 + 2. To compute the binary representation of n, we consider the powers of ii less than or equal to n in decreasing order to determine which belong in the binary decomposition (and therefore represent to a ane bit in the binary representation).
  • Gambler's ruin. gambler's ruin Suppose a gambler makes a serial of off-white $i bets, starting with $50, and continue to play until she either goes bankrupt or has $250. What are the chances that she will go habitation with $250, and how many bets might she expect to make before winning or losing? Gambler.java is a simulation that can help answer these questions. It takes three command-line arguments, the initial stake ($50), the goal amount ($250), and the number of times we want to simulate the game.
  • Prime number factorization. Factors.java takes an integer command-line argument n and prints its prime factorization. In contrast to many of the other programs that we have seen (which nosotros could do in a few minutes with a computer or pencil and paper), this computation would non be feasible without a computer.

Other conditional and loop constructs.

To be complete, we consider four more Java constructs related to conditionals and loops. They are used much less frequently than the

if

,

while

, and

for

statements that nosotros've been working with, simply it is worthwhile to be enlightened of them.

  • Intermission statements. In some situations, we want to firsthand exit a loop without letting information technology run to completion. Java provides the intermission argument for this purpose. Prime.java takes an integer command-line argument due north and prints true if n is prime, and false otherwise. There are 2 different ways to get out this loop: either the break argument is executed (considering n is not prime) or the loop-continuation condition is not satisfied (because n is prime number).

    Note that the break statement does non apply to if or if-else statements. In a famous programming bug, the U.S. telephone network crashed because a developer intended to utilize a break statement to leave a complicated if statement.

  • Continue statements. Coffee also provides a manner to skip to the next iteration of a loop: the keep statement. When a proceed is executed within 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 allow one or two alternatives. Sometimes, a computation naturally suggests more than 2 mutually exclusive alternatives. Java provides the switch statement for this purpose. NameOfDay.java takes an integer between 0 and vi every bit a command-line argument and uses a switch statement to impress the corresponding name of the day (Dominicus to Saturday).
  • Do–while loops. A do-while loop is almost the same as a while loop except that the loop-continuation condition is omitted the first time through the loop. RandomPointInCircle.java sets x and y so that (x, y) is randomly distributed inside the circle centered at (0, 0) with radius 1.
    do-while loop

    With Math.random() we get points that are randomly distributed in the 2-past-two square center at (0, 0). We just generate points in this region until nosotros find one that lies inside the unit disk. We always want to generate at to the lowest degree one point then a do-while loop is most appropriate. We must declare x and y outside the loop since nosotros will want to access their values after the loop terminates.

We don't utilise the following two flow command statements in this textbook, but include them here for abyss.

  • Conditional operator. The conditional operator ?: is a ternary operator (3 operands) that enables you to embed a provisional inside an expression. The 3 operands are separated by the ? and : symbols. If the start operand (a boolean expression) is true, the result has the value of the 2nd expression; otherwise information technology has the value of the third expression.
    int min = (x < y) ? x : y;                
  • Labeled break and go on statements. The intermission and continue statements utilize to the innermost for or while loop. Sometimes we want to jump out of several levels of nested loops. Java provides the labeled interruption and labeled continue statements to accomplish this. Hither is an instance.

Exercises

  1. Write a programme AllEqual.java that takes 3 integer control-line arguments and prints equal if all three are equal, and not equal otherwise.
  2. Write a program RollLoadedDie.java that prints the result of rolling a loaded die such that the probability of getting a 1, two, three, 4, or 5 is ane/8 and the probability of getting a six is three/eight.
  3. Rewrite TenHellos.coffee to make a program Hellos.coffee that takes the number of lines to print as a command-line statement. Yous may presume that the argument is less than k. Hint: consider using i % ten and i % 100 to determine whether to apply "st", "nd", "rd", or "th" for printing the ith Howdy.
  4. Write a program FivePerLine.java that, using 1 for loop and one if statement, prints the integers from 1000 to 2000 with v integers per line. Hint: use the % operator.
  5. Write a program FunctionGrowth.java that prints a table of the values of ln n, n, n ln northward, n2 , north3 , and iin for n = xvi, 32, 64, ..., 2048. Employ tabs ('\t' characters) to line up columns.
  6. What is the value of m and north after executing the following code?
    int n = 123456789; int m = 0; while (n != 0) {    1000 = (10 * m) + (n % ten);    n = due north / x; }                
  7. What does the following code print out?
    int f = 0, m = 1; for (int i = 0; i <= 15; i++) {    Organization.out.println(f);    f = f + g;    1000 = f - g; }                
  8. Unlike the harmonic numbers, the sum i/1 + 1/iv + 1/9 + one/sixteen + ... + ane/due north2 does converge to a constant as n grows to infinity. (Indeed, the constant is π2 / six, so this formula tin can exist used to estimate the value of π.) Which of the post-obit for loops computes this sum? Assume that n is an int initialized to 1000000 and sum is a double initialized to 0.
    (a) for (int i = 1; i <= n; i++)         sum = sum + i / (i * i);  (b) for (int i = 1; i <= n; i++)        sum = sum + 1.0 / i * i;  (c) for (int i = 1; i <= due north; i++)        sum = sum + 1.0 / (i * i);  (d) for (int i = 1; i <= north; i++)        sum = sum + 1 / (1.0 * i * i);                
  9. Modify Binary.java to get a program Alter Kary.java that takes a second command-line argument Chiliad and converts the first argument to base K. Assume the base of operations is between two and 16. For bases greater than 10, use the letters A through F to stand for the 11th through 16th digits, respectively.
  10. Write a program code fragment that puts the binary representation of a positive integer n into a String variable south.

Creative Exercises

  1. Ramanujan's taxi. S. Ramanujan was an Indian mathematician who became famous for his intuition for numbers. When the English mathematician Thou. H. Hardy came to visit him in the hospital one day, Hardy remarked that the number of his taxi was 1729, a rather dull number. To which Ramanujan replied, "No, Hardy! No, Hardy! It is a very interesting number. It is the smallest number expressible as the sum of two cubes in two dissimilar ways." Verify this claim by writing a programme Ramanujan.java that takes an integer control-line argument northward and prints all integers less than or equal to n that can exist expressed as the sum of two cubes in two dissimilar ways - find singled-out positive integers a, b, c, and d such that a3 + b3 = c3 + d3 . Use iv nested for loops.

    At present, the license plate 87539319 seems similar a rather dull number. Determine why it's not.

  2. Checksums. The International Standard Book Number (ISBN) is a 10 digit lawmaking that uniquely specifies a book. The rightmost digit is a checksum digit which can be uniquely adamant from the other 9 digits from the status that di + 2dii + 3d3 + ... + 10d10 must be a multiple of 11 (here di denotes the ith digit from the correct). The checksum digit di can exist any value from 0 to 10: the ISBN convention is to use the value X to announce 10. Example: the checksum digit corresponding to 020131452 is v since is the only value of di between 0 and and ten for which done + ii*2 + iii*5 + iv*4 + 5*i + 6*iii + vii*one + 8*0 + ix*2 + 10*0 is a multiple of 11. Write a program ISBN.java that takes a 9-digit integer as a control-line statement, computes the checksum, and prints the x-digit ISBN number. It's ok if you don't print any leading 0s.
  3. Exponential part. Assume that x is a positive variable of blazon double. Write a program Exp.coffee that computes e^x using the Taylor series expansion
    $$ eastward^ x = one + x + \frac{x^2}{2!} + \frac{10^3}{iii!} + \frac{x^four}{four!} + \ldots $$
  4. Trigonometric functions. Write two programs Sin.java and Cos.java that compute sin x and cos x using the Taylor serial expansions
    $$ \sin 10 = x - \frac{x^iii}{3!} + \frac{x^five}{v!} - \frac{10^7}{7!} + \ldots $$
    $$ \cos ten = ane - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{six!} + \ldots $$
  5. Game simulation. In the game evidence Let'south Make a Bargain, a contestant is presented with three doors. Behind ane door is a valuable prize, behind the other two are gag gifts. Later the contestant chooses a door, the host opens up one of the other two doors (never revealing the prize, of form). The contestant is then given the opportunity to switch to the other unopened door. Should the contestant do so? Intuitively, information technology might seem that the contestant's initial pick door and the other unopened door are as probable to incorporate the prize, so there would be no incentive to switch. Write a programme MonteHall.java to test this intuition by simulation. Your program should accept an integer command-line statement northward, play the game northward times using each of the two strategies (switch or don't switch) and print the chance of success for each strategy. Or you tin play the game here.
  6. Euler's sum-of-powers conjecture. In 1769 Leonhard Euler formulated a generalized version of Fermat's Concluding Theorem, conjecturing that at least north nthursday powers are needed to obtain a sum that is itself an nth ability, for north > ii. Write a programme Euler.java to disprove Euler's theorize (which stood until 1967), using a quintuply nested loop to find four positive integers whose fifth power sums to the 5th power of some other positive integer. That is, detect a, b, c, d, and east such that a 5 + b 5 + c 5 + d v = e 5. Utilise the long data type.

Spider web Exercises

  1. Write a plan RollDie.coffee that generates the result of rolling a fair 6-sided die (an integer between 1 and 6).
  2. Write a program that takes three integer command-line arguments a, b, and c and print the number of distinct values (i, 2, or 3) among a, b, and c.
  3. Write a program that takes v integer command-line arguments and prints the median (the 3rd largest i).
  4. (hard) Now, try to compute the median of five elements such that when executed, information technology never makes more than half dozen total comparisons.
  5. How can I create in an space loop with a for loop?

    Solution: for(;;) is the aforementioned every bit while(true).

  6. What'south incorrect with the following loop?
    boolean done = false; while (done = simulated) {     ... }                
    The while loop condition uses = instead of == and then it is an assignment statement (which makes done always false and the body of the loop will never exist executed). Information technology's improve to mode to avoid using ==.
    boolean done = false; while (!done) {     ... }                
  7. What'due south wrong with the post-obit loop that is intended to compute the sum of the integers ane through 100?
    for (int i = 1; i <= North; i++) {    int sum = 0;    sum = sum + i; } System.out.println(sum);                
    The variable sum should be divers outside the loop. By defining it inside the loop, a new variable sum is initialized to 0 each time through the loop; too it is not even accessible outside the loop.
  8. Write a plan Hurricane.java that that takes the wind speed (in miles per hour) as an integer control-line argument and prints whether it qualifies every bit a hurricane, and if then, whether information technology is a Category 1, ii, iii, 4, or 5 hurricane. Below is a tabular array of the current of air speeds according to the Saffir-Simpson calibration.
    Category Wind Speed (mph)
    1 74 - 95
    2 96 - 110
    iii 111 - 130
    4 131 - 155
    v 155 and above
  9. What is wrong with the following code fragment?
    double ten = -32.ii; boolean isPositive = (x > 0); if (isPositive = truthful) 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).

  10. Change/add 1 character so that the following program prints 20 xs. There are two different solutions.
    int i = 0, n = 20; for (i = 0; i < n; i--)     Organisation.out.print("x");                
    Solution: Replace the i < due north condition with -i < northward. Replace the i-- with northward--. ( In C, there is a 3rd: replace the < with a +.)
  11. What does the following code fragment do?
    if (10 > 0);     Organisation.out.println("positive");                

    Solution: always prints positive regardless of the value of x because of the extra semicolon subsequently the if statement.

  12. RGB to HSB converter. Write a program RGBtoHSV.java that takes an RGB color (three integers between 0 and 255) and transforms it to an HSB colour (three different integers betwixt 0 and 255). Write a program HSVtoRGB.java that applies the inverse transformation.
  13. Boys and girls. A couple beginning a family decides to keep having children until they have at to the lowest degree one of either sex activity. Estimate the average number of children they will accept via simulation. Also estimate the most common outcome (record the frequency counts for two, 3, and 4 children, and also for 5 and above). Assume that the probability p of having a boy or girl is 1/2.
  14. What does the following plan do?
    public static void master(String[] args) {    int Due north = Integer.parseInt(args[0]);    int x = 1;    while (Due north >= 1) {       System.out.println(ten);       x = 2 * ten;       Due north = Northward / 2;    } }                
    Solution: Prints all of the powers of 2 less than or equal to n.
  15. Boys and girls. Repeat the previous question, but assume the couple keeps having children until they have another kid which is of the aforementioned sex as the first child. How does your answer alter if p is dissimilar from 1/ii?

    Surprisingly, the average number of children is ii if p = 0 or one, and iii for all other values of p. Merely the most likely value is 2 for all values of p.

  16. Given two positive integers a and b, what result does the post-obit code fragment leave in c
    c = 0; while (b > 0) {    if (b % ii == 1) c = c + a;    b = b / two;    a = a + a; }                

    Solution: a * b.

  17. Write a plan using a loop and four conditionals to print
    12 midnight 1am 2am ... 12 noon 1pm ... 11pm                
  18. What does the post-obit programme impress?
    public class Exam {    public static void main(Cord[] args) {       if (10 > v);        else; {                      System.out.println("Here");       };    }               }                
  19. Alice tosses a off-white coin until she sees two consecutive heads. Bob tosses some other fair money until he sees a head followed by a tail. Write a program to estimate the probability that Alice will brand fewer tosses than Bob? Solution: 39/121.
  20. Rewrite DayOfWeek.java from Do 1.2.29 so that it prints the day of the calendar week every bit Sunday, Monday, and then forth instead of an integer between 0 and 6. Use a switch argument.
  21. Number-to-English language. Write a program to read in a command line integer between -999,999,999 and 999,999,999 and print the English equivalent. Hither is an exhaustive list of words that your program should use: negative, naught, one, two, iii, four, five, half dozen, seven, eight, ix, ten, xi, twelve, xiii, fourteen, fifteen, xvi, seventeen, eighteen, nineteen, twenty, xxx, forty, fifty, lx, seventy, eighty, xc, hundred, thou, million . Don't utilize hundred, when yous can use one thousand, e.g., utilise k v hundred instead of fifteen hundred. Reference.
  22. Gymnastics judging. A gymnast'south score is determined by a console of 6 judges who each make up one's mind a score betwixt 0.0 and ten.0. The final score is determined by discarding the loftier and depression scores, and averaging the remaining 4. Write a programme GymnasticsScorer.coffee that takes 6 real control line inputs representing the 6 scores and prints their boilerplate, later throwing out the high and depression scores.
  23. Quarterback rating. To compare NFL quarterbacks, the NFL devised a the quarterback rating formula based on the quarterbacks number of completed passes (A), laissez passer attempts (B), passing yards (C), touchdown passes (D), and interception (East) equally follows:
    1. Completion ratio: W = 250/3 * ((A / B) - 0.3).
    2. Yards per pass: X = 25/half-dozen * ((C / B) - 3).
    3. Touchdown ratio: Y = 1000/3 * (D / B)
    4. Interception ratio: Z = 1250/3 * (0.095 - (Due east / B))
    The quarterback rating is computed by summing up the higher up iv quantities, just rounding up or down each value so that it is at least 0 and and at most 475/12. Write a program QuarterbackRating.java that takes 5 command line inputs A, B, C, D, and E, and prints the quarterback rating. Use your program to compute Steve Young'southward 1994 tape-setting season (112.8) in which he completed 324 of 461 passes for three,969 yards, and threw 35 touchdowns and 10 interceptions. As of 2014, the all-fourth dimension unmarried-season record is 122.5 past Aaron Rodgers in 2011.
  24. Decimal expansion of rational numbers. Given 2 integers p and q, the decimal expansion of p/q has an infinitely repeating cycle. For example, ane/33 = 0.03030303.... We use the notation 0.(03) to announce that 03 repeats indefinitely. Equally another example, 8639/70000 = 0.1234(142857). Write a program DecimalExpansion.java that reads in two control line integers p and q and prints the decimal expansion of p/q using the in a higher place notation. Hint: utilize Floyd's rule.
  25. Fri the 13th. What is the maximum number of consecutive days in which no Friday the 13th occurs? Hint: The Gregorian calendar repeats itself every 400 years (146097 days) so y'all only need to worry near a 400 year interval.

    Solution: 426 (e.g., from 8/13/1999 to x/13/2000).

  26. January i. Is Jan 1 more likely to fall on a Sabbatum or Lord's day? Write a plan to make up one's mind the number of times each occurs in a 400 year interval.

    Solution: Sunday (58 times) is more than likely than Saturday (56 times).

  27. What practice the post-obit two lawmaking fragments do?
    for (int i = 0; i < N; i++)    for (int j = 0; j < N; j++)        if (i != j) System.out.println(i + ", " + j);  for (int i = 0; i < N; i++)    for (int j = 0; (i != j) && (j < N); j++)        System.out.println(i + ", " + j);                
  28. Make up one's mind what value gets printed out without using a estimator. Choose the right answer from 0, 100, 101, 517, or 1000.
    int cnt = 0; for (int i = 0; i < ten; i++)    for (int j = 0; j < 10; j++)       for (int k = 0; k < 10; k++)          if (2*i + j >= 3*k)             cnt++; System.out.println(cnt);                
  29. Rewrite CarLoan.java from Creative Exercise XYZ so that information technology properly handles an involvement rate of 0% and avoids dividing by 0.
  30. Write the shortest Java program you can that takes an integer command-line argument northward and prints true if (one + 2 + ... + n) two is equal to (oneiii + 23 + ... + northward3).

    Solution: Always print true.

  31. Modify Sqrt.coffee so that it reports an error if the user enters a negative number and works properly if the user enters zero.
  32. What happens if we initialize t to -x instead of x in program Sqrt.java?
  33. Sample standard deviation of compatible distribution. Alter Exercise eight so that information technology prints the sample standard divergence in add-on to the average.
  34. Sample standard deviation of normal distribution. that takes an integer Northward equally a command-line argument and uses Web Exercise i from Section one.2 to print N standard normal random variables, and their average value, and sample standard deviation.
  35. Loaded dice. [Stephen Rudich] Suppose you have 3, iii sided dice. A: {2, 6, 7}, B: { i, 5, nine}, and C: {iii, iv, 8}. Ii players gyre a dice and the ane with the highest value wins. Which die would y'all choose? Solution: A beats B with probability five/ix, B beats C with probability 5/9 and C beats A with probability v/9. Be sure to cull second!
  36. Thue–Morse sequence. Write a programme ThueMorse.java that reads in a control line integer n and prints the Thue–Morse sequence of society n. The first few strings are 0, 01, 0110, 01101001. Each successive cord is obtained by flipping all of the bits of the previous cord and concatenating the consequence to the end of the previous string. The sequence has many amazing properties. For example, it is a binary sequence that is cube-free: it does not contain 000, 111, 010101, or sss where due south is whatever string. Information technology is self-similar: if you delete every other bit, you get another Thue–Morse sequence. Information technology arises in diverse areas of mathematics as well as chess, graphic design, weaving patterns, and music composition.
  37. Programme Binary.java prints the binary representation of a decimal number n by casting out powers of 2. Write an alternating version Program Binary2.java that is based on the following method: Write 1 if northward is odd, 0 if due north is fifty-fifty. Separate n by ii, throwing away the remainder. Repeat until n = 0 and read the respond backwards. Use % to determine whether n is fifty-fifty, and use string concatenation to form the answer in reverse order.
  38. What does the following code fragment practise?
    int digits = 0; exercise {    digits++;    n = n / x; } while (northward > 0);                

    Solution: The number of bits in the binary representation of a natural number due north. We use a practise-while loop so that lawmaking output ane if northward = 0.

  39. Write a program NPerLine.java that takes an integer command-line argument north and prints the integers from x to 99 with due north integers per line.
  40. Change NPerLine.java so that it prints the integers from 1 to 1000 with n integers per line. Make the integers line up by printing the right number of spaces before an integer (due east.one thousand., three for 1-9, two for ten-99, and ane for 100-999).
  41. Suppose a, b, and c are random number uniformly distributed between 0 and 1. What is the probability that a, b, and c form the side length of some triangle? Hint: they will form a triangle if and only if the sum of every two values is larger than the tertiary.
  42. Repeat the previous question, but summate the probability that the resulting triangle is obtuse, given that the three numbers for a triangle. Hint: the three lengths volition form an birdbrained triangle if and only if (i) the sum of every two values is larger than the third and (ii) the sum of the squares of every 2 side lengths is greater than or equal to the square of the third.

    Answer.

  43. What is the value of due south later on executing the post-obit code?
    int M = 987654321; String s = ""; while (One thousand != 0) {    int digit = M % 10;    s = south + digit;    One thousand = M / 10; }                
  44. What is the value of i after the post-obit confusing code is executed?
    int i = 10; i = i++; i = ++i; i = i++ + ++i;                

    Moral: don't write lawmaking similar this.

  45. Formatted ISBN number. Write a programme ISBN2.java that reads in a nine digit integer from a command-line argument, computes the check digit, and prints the fully formatted ISBN number, e.thou, 0-201-31452-5.
  46. UPC codes. The Universal Product Code (UPC) is a 12 digit code that uniquely specifies a product. The least significant digit d1(rightmost one) is a check digit which is the uniquely determined past making the following expression a multiple of ten:
    (d1 + diii + d5 + d7 + d9 + d11) + 3 (dii + dfour + dhalf-dozen + d8 + dten + d12)

    As an example, the check digit corresponding to 0-48500-00102 (Tropicana Pure Premium Orange Juice) is 8 since

    (8 + 0 + 0 + 0 + 5 + 4) + 3 (2 + 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 command line parameter, computes the cheque digit, and prints the the full UPC. Hint: utilise a variable of type long to store the 11 digit number.

  47. Write a programme that reads in the wind speed (in knots) as a command line statement and prints its strength according to the Beaufort scale. Apply a switch statement.
  48. Making alter. Write a plan that reads in a command line integer Northward (number of pennies) and prints the best way (fewest number of coins) to brand change using U.s. coins (quarters, dimes, nickels, and pennies simply). For example, if N = 73 then impress
    2 quarters 2 dimes iii pennies                

    Hint: use the greedy algorithm. That is, dispense equally many quarters equally possible, then dimes, and so nickels, and finally pennies.

  49. Write a program Triangle.java that takes a command-line argument N and prints an N-past-N triangular pattern like the i below.
    * * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *                
  50. Write a program Ex.java that takes a control-line argument N and prints a (2N + 1)-by-(2N + ane) ex similar the ane beneath. Use two for loops and one if-else statement.
    * . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *                
  51. Write a program BowTie.java that takes a command-line argument N and prints a (2N + 1)-by-(2N + 1) bowtie similar the ane below. Employ 2 for loops and one if-else statement.
    * . . . . . *  * * . . . * *  * * * . * * *  * * * * * * *  * * * . * * *  * * . . . * *  * . . . . . *                
  52. Write a program Diamond.java that takes a control-line argument Northward and prints a (2N + 1)-by-(2N + 1) diamond like the i beneath.
    % java Diamond 4 . . . . * . . . .  . . . * * * . . .  . . * * * * * . .  . * * * * * * * .  * * * * * * * * *  . * * * * * * * .  . . * * * * * . .  . . . * * * . . .  . . . . * . . . .                
  53. Write a program Heart.java that takes a command-line statement N and prints a centre.
  54. What does the plan Circle.coffee impress out when North = 5?
    for (int i = -N; i <= North; i++) {    for (int j = -N; j <= North; j++) {       if (i*i + j*j <= N*N) System.out.print("* ");       else                  System.out.impress(". ");    }    System.out.println(); }                
  55. Seasons. Write a program Season.java that takes two command line integers M and D and prints the flavour corresponding to month M (1 = January, 12 = December) and day D in the northern hemisphere. Utilise the following table
    SEASON FROM TO
    Spring March 21 June twenty
    Summer June 21 September 22
    Autumn September 23 December 21
    Winter Dec 21 March 20
  56. Zodiac signs. Write a program Zodiac.coffee that takes two command line integers M and D and prints the Zodiac sign corresponding to calendar month G (1 = January, 12 = Dec) and day D. Apply the post-obit table
    SIGN FROM TO
    Capricorn December 22 January 19
    Aquarius January 20 February 17
    Pisces February 18 March 19
    Aries March 20 April 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 October 22
    Scorpio October 23 November 21
    Sagittarius November 22 December 21
  57. Muay Thai kickboxing. Write a programme that reads in the weight of a Muay Thai kickboxer (in pounds) equally a command-line argument and prints their weight grade. Use a switch statement.
    Course 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
    Low-cal heavyweight 167 175
    Super low-cal heavyweight 175 183
    Cruiserweight 183 190
    Heavyweight 190 220
    Super heavyweight 220 -
  58. Euler's sum of powers conjecture. In 1769 Euler generalized Fermat'due south Last Theorem and conjectured that information technology is impossible to detect iii quaternary powers whose sum is a 4th ability, or four 5th powers whose sum is a 5th power, etc. The conjecture was disproved in 1966 by exhaustive figurer search. Disprove the theorize by finding positive integers a, b, c, d, and e such that a5 + b5 + c5 + d5= e5. Write a programme Euler.java that reads in a command line parameter N and exhaustively searches for all such solutions with a, b, c, d, and due east less than or equal to Northward. No counterexamples are known for powers greater than 5, just you can join EulerNet, a distributed calculating effort to find a counterexample for sixth powers.
  59. Blackjack. Write a plan Blackjack.java that takes three control line integers ten, y, and z representing your two blackjack cards x and y, and the dealers face-upward card z, and prints the "standard strategy" for a 6 menu deck in Atlantic city. Assume that ten, y, and z are integers between one and x, representing an ace through a face card. Study whether the thespian should hit, stand, or carve up according to these strategy tables. (When you learn almost arrays, you volition encounter an alternate strategy that does not involve every bit many if-else statements).
  60. Blackjack with doubling. Modify the previous practise to let doubling.
  61. Projectile motility. The post-obit equation gives the trajectory of a ballistic missile as a office of the initial angle theta and windspeed: xxxx. Write a java program to print the (x, y) position of the missile at each time step t. Utilise trial and error to determine at what angle you should aim the missile if y'all promise to incinerate a target located 100 miles e of your current location and at the same elevation. Assume the windspeed is 20 mph due east.
  62. World series. The baseball game world series is a all-time of vii contest, where the first team to win four games wins the World Series. Suppose the stronger team has probability p > 1/2 of winning each game. Write a program to approximate the chance that the weaker teams wins the World Serial and to judge how many games on average it will accept.
  63. Consider the equation (ix/4)^x = x^(9/iv). One solution is 9/4. Can you notice some other i using Newton's method?
  64. Sorting networks. Write a program Sort3.java with three if statements (and no loops) that reads in three integers a, b, and c from the command line and prints them out in ascending order.
    if (a > b) bandy a and b if (a > c) bandy a and c if (b > c) swap b and c                
  65. Oblivious sorting network. Convince yourself that the following code fragment rearranges the integers stored in the variables A, B, C, and D and then 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 = Eastward; 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; }                
    Devise a sequence of statements that would sort 5 integers. How many if statements does your programme use?
  66. Optimal oblivious sorting networks. Create a plan that sorts four integers using merely 5 if statements, and one that sorts five integers using only 9 if statements of the type above? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How can you check that your programme works for all inputs?

    Solution: Sort4.java sorts iv elements using v compare-exchanges. Sort5.coffee sorts five elements using 9 compare-exchanges.

    The 0-1 principle asserts that yous can verify the correctness of a (deterministic) sorting algorithm by checking whether information technology correctly sorts an input that is a sequence of 0s and 1s. Thus, to check that Sort5.java works, you only need to examination it on the 2^5 = 32 possible inputs of 0s and 1s.

  67. Optimal oblivious sorting (challenging). Find an optimal sorting network for 6, 7, and eight inputs, using 12, sixteen, and 19 if statements of the grade in the previous problem, respectively.

    Solution: Sort6.java is the solution for sorting 6 elements.

  68. Optimal non-oblivious sorting. Write a program that sorts 5 inputs using only 7 comparisons. Hint: First compare the first two numbers, the second 2 numbers, and the larger of the two groups, and label them so that a < b < d and c < d. Second, insert the remaining chemical element due east into its proper place in the chain a < b < d past first comparing against b, so either a or d depending on the outcome. Tertiary, insert c into the proper place in the concatenation involving a, b, d, and e in the same manner that you lot inserted east (with the knowledge that c < d). This uses 3 (first step) + 2 (second stride) + 2 (tertiary step) = vii comparisons. This method was first discovered past H. B. Demuth in 1956.
  69. Weather balloon. (Etter and Ingber, p. 123) Suppose that h(t) = 0.12t4 + 12t3 - 380t2 + 4100t + 220 represents the summit of a weather balloon at time t (measured in hours) for the first 48 hours afterwards its launch. Create a table of the top at fourth dimension t for t = 0 to 48. What is its maximum height? Solution: t = five.
  70. Volition the following lawmaking fragment compile? If so, what will it practise?
    int a = x, b = 18; if (a = b) Organization.out.println("equal"); else       System.out.println("not equal");                

    Solution: It uses the assignment operator = instead of the equality operator == in the conditional. In Java, the result of this statement is an integer, but the compiler expects a boolean. As a result, the plan will not compile. In some languages (notably C and C++), this code fragment will set the variable a to 18 and print equal without an error.

  71. Gotcha 1. What does the post-obit code fragment exercise?
    boolean a = false; if (a = truthful) Arrangement.out.println("yes"); else          System.out.println("no");                
    Solution: it prints yes. Note that the conditional uses = instead of ==. This means that a is assigned the value true As a result, the conditional expression evaluates to truthful. Coffee is not immune to the = vs. == fault described in the previous exercise. For this reason, it is much better style to use if (a) or if (!a) when testing booleans.
  72. Gotcha ii. What does the following code fragment do?
    int a = 17, x = 5, y = 12; if (x > y); {    a = xiii;    ten = 23; } Organisation.out.println(a);                
    Solution: Ever prints 13 since there is a spurious semicolon after the if statement. Thus, the assignment statement a = thirteen; will be executed fifty-fifty though (ten <= y) It is legal (but uncommon) to have a block that does not belong to a conditional statement, loop, or method.
  73. Gotcha 3. What does the following code fragment do?
    for (int x = 0; 10 < 100; x += 0.five) {     System.out.println(x); }                
    Solution: It goes into an infinite loop printing 0. The compound assignment argument ten += 0.five is equivalent to x = (int) (10 + 0.v).
  74. What does the post-obit code fragment do?
    int income = Integer.parseInt(args[0]); if (income >= 311950) charge per unit = .35; if (income >= 174700) rate = .33; if (income >= 114650) rate = .28; if (income >=  47450) rate = .25; if (income >=      0) charge per unit = .22; System.out.println(rate);                
    It does non compile because the compile cannot guarantee that rate is initialized. Use if-else instead.
  75. Application of Newton's method. Write a program BohrRadius.coffee that finds the radii where the probability of finding the electron in the 4s excited state of hydrogen is zero. The probability is given by: (1 - 3r/iv + rii/8 - r3/192)2 e-r/2 , where r is the radius in units of the Bohr radius (0.529173E-8 cm). Utilize Newton's method. By starting Newton's method at unlike values of r, y'all tin discover all three roots. Hint: employ initial values of r= 0, 5, and thirteen. Challenge: explicate what happens if you lot use an initial value of r = 4 or 12.
  76. Pepys trouble. In 1693, Samuel Pepys asked Isaac Newton which was more than probable: getting at least one i when rolling a fair die 6 times or getting at to the lowest degree two 1's when rolling a fair die 12 times. Write a program Pepys.java that uses simulation to determine the correct answer.
  77. What is the value of the variable s after running the following loop when N = 1, 2, three, 4, and 5.
    String s = ""; for (int i = 1; i <= Northward; i++) {    if (i % 2 == 0) s = south + i + south;    else            s = i + s + i; }                

    Solution: Palindrome.java.

  78. Body mass index. The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a plan BMI.coffee that takes two control-line arguments, weight and height, computes the BMI, and prints the corresponding BMI category:
    • Starvation: less than fifteen
    • Anorexic: less than 17.5
    • Underweight: less than xviii.5
    • Ideal: greater than or equal to 18.5 simply less than 25
    • Overweight: greater than or equal to 25 but less than 30
    • Obese: greater than or equal to 30 but less than 40
    • Morbidly Obese: greater than or equal to twoscore
  79. Reynolds number. The Reynolds number is the ratio if inertial forces to mucilaginous forces and is an of import quantity in fluid dynamics. Write a program that takes in 4 command-line arguments, the diameter d, the velocity v, the density rho, and the viscosity mu, and prints the Reynold's number d * v * rho / mu (bold all arguments are in SI units). If the Reynold's number is less than 2000, print laminar flow, if it's between 2000 and 4000, print transient menstruation, and if it's more than 4000, print turbulent period.
  80. Air current chill revisited. The wind arctic formula from Exercise one.two.14 is only valid if the wind speed is above 3MPH and below 110MPH and the temperature is beneath 50 degrees Fahrenheit and to a higher place -50 degrees. Modify your solution to impress an error message if the user types in a value outside the allowable range.
  81. Indicate on a sphere. Write a program to print the (x, y, z) coordinates of a random point on the surface of a sphere. Use Marsaglia' method: option a random bespeak (a, b) in the unit circle as in the do-while example. Then, set x = 2a sqrt(ane - a^2 - b^2), y = 2b sqrt(i - a^2 - b^ii), z = 1 - 2(a^2 + b^2).
  82. Powers of k. Write a program PowersOfK.coffee that takes an integer Yard as control-line argument and prints all the positive powers of K in the Java long data type. Note: the abiding Long.MAX_VALUE is the value of the largest integer in long.
  83. Square root, revisited. Why not utilise the loop-continuation condition (Math.abs(t*t - c) > EPSILON) in Sqrt.coffee instead of Math.abs(t - c/t) > t*EPSILON)?

    Solution: Surprisingly, information technology can pb to inaccurate results or worse. For example, if you supply SqrtBug.java with the command-line argument 1e-50, you go 1e-fifty as the answer (instead of 1e-25); if you supply 16664444, you get an space loop!

  84. What happens when you effort to compile the following code fragment?
    double x;   if (a >= 0) x = iii.14; if (a <  0) ten = ii.71; System.out.println(x);                

    Solution: It complains that the variable x might not have been initialized (even though nosotros can clearly see that x volition be initialized by one of the two if statements). You lot can avoid this problem here by using if-else.

Write a Loop That Reads Positive Integers From Standard Input and That Terminates

Source: https://introcs.cs.princeton.edu/java/13flow/

0 Response to "Write a Loop That Reads Positive Integers From Standard Input and That Terminates"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel