E Program Stops Reading Integers Once the User Enters the Same Value Three Times Consecutively

ane.3   Conditionals and Loops

In the programs that nosotros accept examined to this point, each of the statements is executed once, in the club given. Near programs are more complicated because the sequence of statements and the number of times each is executed tin vary. Nosotros use the term control flow to refer to statement sequencing in a program.

If statements.

Near computations require unlike actions for different inputs.

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

While loops.

Many computations are inherently repetitive. The

while

loop enables united states of america to execute a group of statements many times. This enables united states of america to express lengthy computations without writing lots of code.

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

For loops.

The for loop is an alternate Java construct that allows us even more flexibility when writing loops.

  • For note. Many loops follow the same basic scheme: initialize an index variable to some value then use a while loop to test an leave condition involving the index variable, using the last statement in the while loop to modify the index variable. Coffee's for loop is a direct fashion to express such loops.
    anatomy of a for loop
  • Chemical compound assignment idioms. The idiom i++ is a autograph note for i = i + 1.
  • Scope. The telescopic of a variable is the function of the program that can refer to that variable by name. By and large the scope of a variable comprises the statements that follow the declaration in the aforementioned block as the declaration. For this purpose, the lawmaking in the for loop header is considered to be in the aforementioned cake as the for loop body.

Nesting.

The

if

,

while

, and

for

statements accept the same condition as assignment statements or any other statements in Java; that is, nosotros can utilise them wherever a statement is called for. In particular, nosotros tin can apply one or more of them in the body of another statement to make chemical compound statements. To emphasize the nesting, we employ indentation in the program lawmaking.

  • DivisorPattern.coffee has a for loop whose body contains a for loop (whose body is an if-else statement) and a print statement. 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 taxation rate for a given income. Information technology uses several nested if-else statements to exam from amongst a number of mutually sectional possibilities.

Loop examples.

examples of loops

Applications.

The ability to program with loops and conditionals immediately opens up the world of computation to us.

  • Ruler subdivisions. RulerN.java takes an integer command-line argument northward and prints the cord of ruler subdivision lengths. This program illustrates one of the essential characteristics of loops—the plan could hardly be simpler, but information technology can produce a huge amount of output.
  • Harmonic numbers
  • Finite sums. The computational paradigm used in PowersOfTwo.java is 1 that y'all volition use frequently. It uses two variables—one every bit an index that controls a loop, and the other to accumulate a computational upshot. Program HarmonicNumber.coffee uses the same epitome to evaluate the sum
    $$ H_n = \frac{1}{one} + \frac{1}{2} + \frac{ane}{three} + \frac{ane}{4} + \; \ldots \; + \frac{one}{north} $$

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

  • Newton's method. Newton's method Sqrt.coffee uses a classic iterative technique known as Newton'southward method to compute the square root of a positive number x: Beginning with an judge t. If t is equal to 10/t (up to machine precision), then t is equal to a square root of x, so the ciphering is complete. If not, refine the gauge by replacing t with the average of t and x/t. Each time we perform this update, we go closer to the desired answer.
  • Number conversion. Binary.java prints the binary (base 2) representation of the decimal number typed as the command-line argument. 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 proverb that 106 = 64 + 32 + 8 + 2. To compute the binary representation of n, we consider the powers of 2 less than or equal to n in decreasing club to determine which belong in the binary decomposition (and therefore correspond to a 1 bit in the binary representation).
  • Gambler'south ruin. gambler's ruin Suppose a gambler makes a serial of fair $1 bets, starting with $50, and continue to play until she either goes broke or has $250. What are the chances that she will go home with $250, and how many bets might she expect to make before winning or losing? Gambler.coffee is a simulation that can help answer these questions. It takes three control-line arguments, the initial stake ($fifty), the goal amount ($250), and the number of times we want to simulate the game.
  • Prime factorization. Factors.java takes an integer command-line argument due north and prints its prime number factorization. In dissimilarity to many of the other programs that we accept seen (which we could do in a few minutes with a figurer or pencil and paper), this computation would non exist feasible without a reckoner.

Other conditional and loop constructs.

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

if

,

while

, and

for

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

  • Break statements. In some situations, we desire to immediate exit a loop without letting information technology run to completion. Java provides the break statement for this purpose. Prime.java takes an integer control-line argument n and prints truthful if north is prime, and false otherwise. There are two unlike ways to leave this loop: either the break argument is executed (because n is not prime) or the loop-continuation condition is not satisfied (because n is prime).

    Note that the pause statement does not utilise to if or if-else statements. In a famous programming bug, the U.S. telephone network crashed because a programmer intended to utilize a break statement to exit a complicated if statement.

  • Continue statements. Java also provides a way to skip to the next iteration of a loop: the continue statement. When a keep is executed within the body of a for loopy, the menstruation of control transfers straight 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 than 2 mutually exclusive alternatives. Java provides the switch statement for this purpose. NameOfDay.coffee takes an integer between 0 and six as a command-line argument and uses a switch argument to print the corresponding name of the mean solar day (Sunday to Saturday).
  • Do–while loops. A do-while loop is about the aforementioned as a while loop except that the loop-continuation condition is omitted the kickoff time through the loop. RandomPointInCircle.java sets x and y and so that (ten, 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-2 square middle at (0, 0). Nosotros simply generate points in this region until we observe one that lies inside the unit disk. Nosotros always want to generate at least one point and so a practice-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.

Nosotros don't use the following two menses control statements in this textbook, just include them hither for completeness.

  • Conditional operator. The provisional operator ?: is a ternary operator (3 operands) that enables you to embed a provisional within an expression. The 3 operands are separated past the ? and : symbols. If the first operand (a boolean expression) is true, the effect has the value of the second expression; otherwise information technology has the value of the tertiary expression.
    int min = (x < y) ? 10 : y;                
  • Labeled break and continue statements. The break and continue statements apply to the innermost for or while loop. Sometimes we want to spring out of several levels of nested loops. Java provides the labeled pause and labeled continue statements to accomplish this. Here is an example.

Exercises

  1. Write a plan AllEqual.java that takes 3 integer command-line arguments and prints equal if all three are equal, and not equal otherwise.
  2. Write a program RollLoadedDie.java that prints the effect of rolling a loaded die such that the probability of getting a 1, two, three, 4, or 5 is ane/eight and the probability of getting a 6 is three/eight.
  3. Rewrite TenHellos.java to make a plan Hellos.java that takes the number of lines to impress as a command-line argument. Y'all may presume that the argument is less than 1000. Hint: consider using i % x and i % 100 to determine whether to use "st", "nd", "rd", or "thursday" for printing the ith Hello.
  4. Write a program FivePerLine.java that, using one for loop and ane if statement, prints the integers from grand to 2000 with five integers per line. Hint: employ the % operator.
  5. Write a program FunctionGrowth.java that prints a table of the values of ln n, northward, n ln n, northward2 , due north3 , and 2north for n = sixteen, 32, 64, ..., 2048. Utilize tabs ('\t' characters) to line up columns.
  6. What is the value of m and n after executing the following code?
    int n = 123456789; int m = 0; while (northward != 0) {    m = (10 * g) + (n % 10);    northward = n / ten; }                
  7. What does the following code impress out?
    int f = 0, g = 1; for (int i = 0; i <= 15; i++) {    Organisation.out.println(f);    f = f + g;    g = f - k; }                
  8. Unlike the harmonic numbers, the sum one/1 + 1/4 + 1/9 + 1/sixteen + ... + 1/n2 does converge to a constant as north grows to infinity. (Indeed, the constant is πtwo / 6, so this formula can be used to judge the value of π.) Which of the following for loops computes this sum? Assume that due north is an int initialized to 1000000 and sum is a double initialized to 0.
    (a) for (int i = ane; i <= n; i++)         sum = sum + 1 / (i * i);  (b) for (int i = ane; i <= n; i++)        sum = sum + 1.0 / i * i;  (c) for (int i = 1; i <= north; i++)        sum = sum + i.0 / (i * i);  (d) for (int i = one; i <= n; i++)        sum = sum + ane / (1.0 * i * i);                
  9. Alter Binary.coffee to get a program Modify Kary.java that takes a 2nd command-line argument K and converts the first argument to base of operations K. Assume the base is betwixt 2 and 16. For bases greater than 10, utilize the letters A through F to represent 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 s.

Creative Exercises

  1. Ramanujan'due south taxi. Southward. Ramanujan was an Indian mathematician who became famous for his intuition for numbers. When the English mathematician Yard. H. Hardy came to visit him in the hospital one solar day, Hardy remarked that the number of his taxi was 1729, a rather dull number. To which Ramanujan replied, "No, Hardy! No, Hardy! Information technology is a very interesting number. Information technology is the smallest number expressible as the sum of two cubes in 2 unlike ways." Verify this merits past writing a programme Ramanujan.java that takes an integer command-line argument n and prints all integers less than or equal to n that tin can exist expressed as the sum of two cubes in ii different ways - find singled-out positive integers a, b, c, and d such that a3 + biii = c3 + d3 . Employ four nested for loops.

    At present, the license plate 87539319 seems like a rather wearisome number. Determine why information technology'south non.

  2. 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 ix digits from the condition that di + 2d2 + 3d3 + ... + 10d10 must be a multiple of 11 (here di denotes the ith digit from the right). The checksum digit d1 can be any value from 0 to ten: the ISBN convention is to apply the value X to denote 10. Example: the checksum digit corresponding to 020131452 is 5 since is the only value of d1 between 0 and and 10 for which d1 + 2*2 + 3*5 + 4*iv + 5*1 + half-dozen*3 + vii*1 + eight*0 + nine*2 + x*0 is a multiple of 11. Write a programme ISBN.coffee that takes a 9-digit integer as a control-line argument, computes the checksum, and prints the 10-digit ISBN number. Information technology's ok if you don't impress any leading 0s.
  3. Exponential function. Presume that ten is a positive variable of type double. Write a program Exp.java that computes east^x using the Taylor serial expansion
    $$ e^ x = 1 + x + \frac{x^ii}{2!} + \frac{x^3}{iii!} + \frac{x^iv}{four!} + \ldots $$
  4. Trigonometric functions. Write ii programs Sin.coffee and Cos.java that compute sin x and cos ten using the Taylor series expansions
    $$ \sin 10 = ten - \frac{x^3}{3!} + \frac{ten^5}{v!} - \frac{x^7}{seven!} + \ldots $$
    $$ \cos 10 = one - \frac{ten^2}{2!} + \frac{x^4}{4!} - \frac{x^half dozen}{6!} + \ldots $$
  5. Game simulation. In the game show Let'south Make a Bargain, a contestant is presented with iii doors. Behind one door is a valuable prize, behind the other ii are gag gifts. Later on the contestant chooses a door, the host opens upward i of the other 2 doors (never revealing the prize, of course). The contestant is then given the opportunity to switch to the other unopened door. Should the contestant practise and then? Intuitively, information technology might seem that the contestant's initial choice door and the other unopened door are equally likely to contain the prize, and then there would be no incentive to switch. Write a plan MonteHall.java to exam this intuition by simulation. Your program should have an integer command-line statement n, play the game n 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 Last Theorem, conjecturing that at least northward nth powers are needed to obtain a sum that is itself an nth ability, for northward > 2. Write a programme Euler.java to disprove Euler's conjecture (which stood until 1967), using a quintuply nested loop to find four positive integers whose 5th power sums to the fifth power of another positive integer. That is, notice a, b, c, d, and e such that a 5 + b five + c 5 + d five = e 5. Utilize the long data type.

Web Exercises

  1. Write a program RollDie.java that generates the result of rolling a fair half-dozen-sided die (an integer between 1 and half dozen).
  2. Write a programme that takes 3 integer command-line arguments a, b, and c and print the number of distinct values (1, 2, or iii) amongst a, b, and c.
  3. Write a program that takes five integer command-line arguments and prints the median (the third largest i).
  4. (difficult) At present, endeavor to compute the median of 5 elements such that when executed, information technology never makes more than than 6 full comparisons.
  5. How tin I create in an infinite loop with a for loop?

    Solution: for(;;) is the same as while(true).

  6. What'due south incorrect with the following loop?
    boolean done = faux; while (done = imitation) {     ... }                
    The while loop condition uses = instead of == and then it is an consignment argument (which makes done always fake and the body of the loop will never be executed). It'southward improve to style to avoid using ==.
    boolean done = faux; while (!done) {     ... }                
  7. What's incorrect with the post-obit loop that is intended to compute the sum of the integers 1 through 100?
    for (int i = one; i <= N; i++) {    int sum = 0;    sum = sum + i; } System.out.println(sum);                
    The variable sum should be defined outside the loop. Past defining it inside the loop, a new variable sum is initialized to 0 each fourth dimension through the loop; also it is not even attainable exterior the loop.
  8. Write a plan Hurricane.java that that takes the wind speed (in miles per hour) as an integer command-line argument and prints whether it qualifies as a hurricane, and if and so, whether it is a Category 1, two, three, 4, or five hurricane. Below is a table of the wind speeds according to the Saffir-Simpson scale.
    Category Wind Speed (mph)
    1 74 - 95
    2 96 - 110
    3 111 - 130
    four 131 - 155
    5 155 and to a higher place
  9. What is incorrect with the following code fragment?
    double x = -32.2; boolean isPositive = (ten > 0); if (isPositive = true) System.out.println(ten + " is positive"); else                   Organization.out.println(10 + " is not positive");                

    Solution: It uses the assignment operator = instead of the equality operator ==. A meliorate solution is to write if (isPositive).

  10. Change/add one graphic symbol and then that the following program prints 20 xs. There are ii dissimilar solutions.
    int i = 0, n = 20; for (i = 0; i < n; i--)     Organization.out.impress("ten");                
    Solution: Replace the i < n condition with -i < n. Replace the i-- with n--. ( In C, there is a third: replace the < with a +.)
  11. What does the post-obit code fragment do?
    if (x > 0);     Organisation.out.println("positive");                

    Solution: e'er prints positive regardless of the value of x considering of the extra semicolon after the if statement.

  12. RGB to HSB converter. Write a programme RGBtoHSV.java that takes an RGB color (three integers between 0 and 255) and transforms it to an HSB color (three unlike integers between 0 and 255). Write a program HSVtoRGB.java that applies the inverse transformation.
  13. Boys and girls. A couple beginning a family decides to continue having children until they have at least one of either sex. Estimate the average number of children they volition have via simulation. Also estimate the nigh common issue (record the frequency counts for two, three, 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 exercise?
    public static void main(String[] args) {    int North = Integer.parseInt(args[0]);    int x = 1;    while (N >= one) {       System.out.println(x);       x = two * x;       N = N / two;    } }                
    Solution: Prints all of the powers of 2 less than or equal to n.
  15. 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 as the kickoff child. How does your reply change if p is dissimilar from 1/2?

    Surprisingly, the boilerplate number of children is two if p = 0 or 1, and iii for all other values of p. But the about likely value is two for all values of p.

  16. Given two positive integers a and b, what result does the following lawmaking 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.

  17. Write a programme using a loop and four conditionals to print
    12 midnight 1am 2am ... 12 noon 1pm ... 11pm                
  18. What does the following plan impress?
    public course Test {    public static void main(Cord[] args) {       if (10 > five);        else; {                      System.out.println("Here");       };    }               }                
  19. Alice tosses a fair coin until she sees 2 consecutive heads. Bob tosses another fair coin until he sees a head followed by a tail. Write a program to gauge the probability that Alice will make fewer tosses than Bob? Solution: 39/121.
  20. Rewrite DayOfWeek.java from Exercise 1.2.29 and then that information technology prints the day of the week every bit Sunday, Monday, 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 language equivalent. Hither is an exhaustive list of words that your plan should use: negative, zero, one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, 13, fourteen, fifteen, 16, seventeen, eighteen, 19, 20, thirty, forty, fifty, lx, seventy, 80, ninety, hundred, thousand, 1000000 . Don't use hundred, when you can use chiliad, e.g., use one thousand v hundred instead of fifteen hundred. Reference.
  22. Gymnastics judging. A gymnast's score is adamant by a panel of six judges who each decide a score between 0.0 and x.0. The final score is determined past discarding the high and low scores, and averaging the remaining 4. Write a plan GymnasticsScorer.java that takes half-dozen real command line inputs representing the 6 scores and prints their boilerplate, afterward throwing out the high and low 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), pass attempts (B), passing yards (C), touchdown passes (D), and interception (East) as follows:
    1. Completion ratio: W = 250/3 * ((A / B) - 0.3).
    2. Yards per laissez passer: X = 25/six * ((C / B) - iii).
    3. Touchdown ratio: Y = m/3 * (D / B)
    4. Interception ratio: Z = 1250/3 * (0.095 - (E / B))
    The quarterback rating is computed by summing upwards the above four quantities, but rounding upwardly or downward each value so that it is at least 0 and and at most 475/12. Write a program QuarterbackRating.coffee that takes five command line inputs A, B, C, D, and E, and prints the quarterback rating. Use your programme to compute Steve Immature's 1994 tape-setting flavour (112.eight) 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.five by 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, i/33 = 0.03030303.... We use the annotation 0.(03) to denote that 03 repeats indefinitely. Equally another example, 8639/70000 = 0.1234(142857). Write a program DecimalExpansion.coffee that reads in two command line integers p and q and prints the decimal expansion of p/q using the above notation. Hint: use Floyd'south rule.
  25. Friday the 13th. What is the maximum number of sequent days in which no Friday the 13th occurs? Hint: The Gregorian agenda repeats itself every 400 years (146097 days) so you merely need to worry about a 400 year interval.

    Solution: 426 (e.m., from 8/thirteen/1999 to ten/13/2000).

  26. January i. Is January 1 more probable to fall on a Sat or Lord's day? Write a program to decide the number of times each occurs in a 400 year interval.

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

  27. What do the following two lawmaking fragments practise?
    for (int i = 0; i < N; i++)    for (int j = 0; j < N; j++)        if (i != j) Organisation.out.println(i + ", " + j);  for (int i = 0; i < N; i++)    for (int j = 0; (i != j) && (j < N); j++)        Organisation.out.println(i + ", " + j);                
  28. Determine what value gets printed out without using a computer. Choose the right reply from 0, 100, 101, 517, or grand.
    int cnt = 0; for (int i = 0; i < 10; i++)    for (int j = 0; j < x; j++)       for (int m = 0; k < 10; k++)          if (2*i + j >= 3*k)             cnt++; Arrangement.out.println(cnt);                
  29. Rewrite CarLoan.java from Creative Exercise XYZ and then that information technology properly handles an interest rate of 0% and avoids dividing by 0.
  30. Write the shortest Java programme you tin that takes an integer command-line argument n and prints truthful if (ane + 2 + ... + n) ii is equal to (13 + twothree + ... + n3).

    Solution: Always impress true.

  31. Modify Sqrt.java and so that it reports an fault if the user enters a negative number and works properly if the user enters zippo.
  32. What happens if we initialize t to -x instead of ten in program Sqrt.java?
  33. Sample standard divergence of uniform distribution. Modify Exercise 8 so that it prints the sample standard deviation in addition to the boilerplate.
  34. Sample standard divergence of normal distribution. that takes an integer Due north every bit a command-line argument and uses Web Exercise 1 from Section 1.2 to print Due north standard normal random variables, and their boilerplate value, and sample standard deviation.
  35. Loaded dice. [Stephen Rudich] Suppose you have iii, three sided die. A: {2, 6, 7}, B: { 1, 5, 9}, and C: {3, 4, 8}. Two players roll a dice and the i with the highest value wins. Which dice would you cull? Solution: A beats B with probability 5/9, B beats C with probability 5/9 and C beats A with probability 5/nine. Be certain to choose second!
  36. Thue–Morse sequence. Write a program ThueMorse.java that reads in a command line integer due north and prints the Thue–Morse sequence of society n. The first few strings are 0, 01, 0110, 01101001. Each successive string is obtained by flipping all of the bits of the previous cord and concatenating the result to the cease of the previous cord. The sequence has many astonishing properties. For example, it is a binary sequence that is cube-free: information technology does not contain 000, 111, 010101, or sss where southward is whatever cord. It is self-like: if you delete every other bit, you lot get another Thue–Morse sequence. It arises in diverse areas of mathematics as well as chess, graphic design, weaving patterns, and music composition.
  37. Program Binary.java prints the binary representation of a decimal number n by casting out powers of 2. Write an alternate version Program Binary2.coffee that is based on the following method: Write 1 if n is odd, 0 if n is even. Separate n by 2, throwing away the residue. Repeat until n = 0 and read the answer backwards. Use % to determine whether n is even, and use string chain to grade the reply in reverse society.
  38. What does the following code fragment do?
    int digits = 0; do {    digits++;    n = n / 10; } while (n > 0);                

    Solution: The number of $.25 in the binary representation of a natural number due north. We apply a do-while loop so that lawmaking output one if northward = 0.

  39. 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.
  40. Modify NPerLine.java and so that it prints the integers from 1 to 1000 with northward integers per line. Brand the integers line up by press the right number of spaces before an integer (e.one thousand., three for 1-ix, two for 10-99, and one for 100-999).
  41. Suppose a, b, and c are random number uniformly distributed betwixt 0 and 1. What is the probability that a, b, and c form the side length of some triangle? Hint: they will grade a triangle if and merely if the sum of every two values is larger than the third.
  42. Repeat the previous question, but calculate the probability that the resulting triangle is birdbrained, given that the three numbers for a triangle. Hint: the iii lengths will form an obtuse triangle if and only if (i) the sum of every two values is larger than the third and (two) the sum of the squares of every 2 side lengths is greater than or equal to the square of the tertiary.

    Respond.

  43. What is the value of s after executing the post-obit code?
    int G = 987654321; String due south = ""; while (Thousand != 0) {    int digit = One thousand % 10;    southward = due south + digit;    G = M / 10; }                
  44. 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 similar this.

  45. Formatted ISBN number. Write a plan ISBN2.java that reads in a 9 digit integer from a control-line argument, computes the check digit, and prints the fully formatted ISBN number, e.g, 0-201-31452-5.
  46. UPC codes. The Universal Product Code (UPC) is a 12 digit code that uniquely specifies a product. The to the lowest degree significant digit dane(rightmost ane) is a check digit which is the uniquely determined by making the following expression a multiple of x:
    (d1 + d3 + d5 + d7 + d9 + dxi) + 3 (d2 + d4 + d6 + deight + d10 + d12)

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

    (viii + 0 + 0 + 0 + 5 + iv) + iii (2 + ane + 0 + 0 + 8 + 0) = 50

    and 50 is a multiple of ten. Write a program that reads in a xi digit integer from a command line parameter, computes the bank check digit, and prints the the full UPC. Hint: use a variable of blazon long to store the xi digit number.

  47. Write a program that reads in the wind speed (in knots) as a command line argument and prints its force according to the Beaufort scale. Use a switch statement.
  48. Making change. Write a plan that reads in a command line integer North (number of pennies) and prints the best way (fewest number of coins) to brand alter using US coins (quarters, dimes, nickels, and pennies only). For example, if N = 73 so print
    2 quarters ii dimes 3 pennies                

    Hint: use the greedy algorithm. That is, manipulate every bit many quarters as possible, so dimes, then nickels, and finally pennies.

  49. Write a program Triangle.java that takes a command-line argument Due north and prints an N-past-N triangular blueprint similar the one below.
    * * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *                
  50. Write a program Ex.java that takes a command-line argument Due north and prints a (2N + 1)-past-(2N + 1) ex similar the one below. Use 2 for loops and i if-else statement.
    * . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *                
  51. Write a program BowTie.java that takes a command-line argument N and prints a (2N + 1)-by-(2N + ane) bowtie similar the one below. Use two for loops and i if-else statement.
    * . . . . . *  * * . . . * *  * * * . * * *  * * * * * * *  * * * . * * *  * * . . . * *  * . . . . . *                
  52. Write a programme Diamond.coffee that takes a command-line argument N and prints a (2N + 1)-by-(2N + 1) diamond like the ane below.
    % java Diamond four . . . . * . . . .  . . . * * * . . .  . . * * * * * . .  . * * * * * * * .  * * * * * * * * *  . * * * * * * * .  . . * * * * * . .  . . . * * * . . .  . . . . * . . . .                
  53. Write a program Heart.coffee that takes a command-line argument N and prints a heart.
  54. What does the program Circle.java impress out when N = 5?
    for (int i = -N; i <= N; i++) {    for (int j = -N; j <= N; j++) {       if (i*i + j*j <= N*North) System.out.print("* ");       else                  System.out.impress(". ");    }    System.out.println(); }                
  55. Seasons. Write a plan Season.java that takes two control line integers M and D and prints the season corresponding to month G (ane = Jan, 12 = Dec) and mean solar day D in the northern hemisphere. Use the following table
    SEASON FROM TO
    Spring March 21 June twenty
    Summertime June 21 September 22
    Fall September 23 December 21
    Winter December 21 March 20
  56. Zodiac signs. Write a program Zodiac.coffee that takes two command line integers Thousand and D and prints the Zodiac sign corresponding to calendar month M (i = January, 12 = December) and day D. Use the following table
    SIGN FROM TO
    Capricorn December 22 January 19
    Aquarius January 20 February 17
    Pisces Feb 18 March 19
    Aries March xx April 19
    Taurus April xx May twenty
    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 Oct 23 November 21
    Sagittarius November 22 December 21
  57. Muay Thai kickboxing. Write a program that reads in the weight of a Muay Thai kickboxer (in pounds) as a command-line argument and prints their weight course. Use a switch statement.
    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 -
  58. Euler's sum of powers conjecture. In 1769 Euler generalized Fermat's Final Theorem and conjectured that it is incommunicable to notice iii 4th powers whose sum is a 4th power, or 4 fifth powers whose sum is a 5th power, etc. The conjecture was disproved in 1966 by exhaustive calculator search. Disprove the conjecture by finding positive integers a, b, c, d, and eastward 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 e less than or equal to N. No counterexamples are known for powers greater than 5, only you tin can join EulerNet, a distributed computing effort to notice a counterexample for sixth powers.
  59. Blackjack. Write a plan Blackjack.java that takes iii command line integers 10, y, and z representing your 2 blackjack cards x and y, and the dealers face up-up card z, and prints the "standard strategy" for a half-dozen card deck in Atlantic city. Assume that x, y, and z are integers between 1 and 10, representing an ace through a face card. Written report whether the role player should hit, stand up, or split according to these strategy tables. (When y'all learn about arrays, y'all will run across an alternating strategy that does not involve as many if-else statements).
  60. Blackjack with doubling. Modify the previous practice to allow doubling.
  61. Projectile motility. The following equation gives the trajectory of a ballistic missile as a part of the initial bending theta and windspeed: xxxx. Write a coffee program to print the (ten, y) position of the missile at each time step t. Use trial and error to determine at what bending yous 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.
  62. Earth series. The baseball game globe series is a best of 7 competition, where the showtime team to win four games wins the Globe Serial. Suppose the stronger team has probability p > 1/2 of winning each game. Write a program to estimate the chance that the weaker teams wins the World Series and to approximate how many games on average information technology will take.
  63. Consider the equation (9/4)^ten = x^(9/4). One solution is ix/four. Can y'all find some other i using Newton'southward 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) swap a and c if (b > c) bandy 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 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 > E) { t = D; D = E; 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 program employ?
  66. Optimal oblivious sorting networks. Create a program that sorts four integers using only v if statements, and one that sorts 5 integers using only nine if statements of the type above? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How can yous check that your program works for all inputs?

    Solution: Sort4.coffee sorts 4 elements using v 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 past checking whether information technology correctly sorts an input that is a sequence of 0s and 1s. Thus, to check that Sort5.java works, y'all only need to test 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 8 inputs, using 12, 16, and xix if statements of the form in the previous problem, respectively.

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

  68. Optimal non-oblivious sorting. Write a plan that sorts 5 inputs using only 7 comparisons. Hint: First compare the first ii numbers, the second two numbers, and the larger of the 2 groups, and characterization them so that a < b < d and c < d. 2d, insert the remaining element e into its proper identify in the chain a < b < d past starting time comparing against b, then either a or d depending on the outcome. Third, insert c into the proper place in the concatenation involving a, b, d, and e in the aforementioned manner that you inserted east (with the knowledge that c < d). This uses 3 (showtime step) + 2 (second stride) + 2 (third pace) = 7 comparisons. This method was first discovered by H. B. Demuth in 1956.
  69. Weather balloon. (Etter and Ingber, p. 123) Suppose that h(t) = 0.12tiv + 12tthree - 380t2 + 4100t + 220 represents the height of a weather balloon at time t (measured in hours) for the first 48 hours later on its launch. Create a table of the height at fourth dimension t for t = 0 to 48. What is its maximum summit? Solution: t = 5.
  70. Volition the following lawmaking fragment compile? If so, what volition it practice?
    int a = 10, b = 18; if (a = b) System.out.println("equal"); else       System.out.println("not equal");                

    Solution: Information technology 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. Every bit a result, the program will not compile. In some languages (notably C and C++), this code fragment will prepare the variable a to 18 and impress equal without an error.

  71. Gotcha 1. What does the following code fragment practise?
    boolean a = false; if (a = true) System.out.println("aye"); else          System.out.println("no");                
    Solution: it prints yeah. Note that the conditional uses = instead of ==. This means that a is assigned the value true As a result, the conditional expression evaluates to true. Java is not allowed to the = vs. == error described in the previous practice. For this reason, it is much better style to utilize if (a) or if (!a) when testing booleans.
  72. Gotcha two. What does the following code fragment do?
    int a = 17, x = five, y = 12; if (x > y); {    a = 13;    x = 23; } System.out.println(a);                
    Solution: E'er prints 13 since at that place is a spurious semicolon afterwards the if statement. Thus, the assignment statement a = 13; volition be executed even though (ten <= y) It is legal (but uncommon) to have a cake that does not belong to a conditional statement, loop, or method.
  73. Gotcha three. What does the following code fragment do?
    for (int 10 = 0; x < 100; 10 += 0.5) {     Organisation.out.println(x); }                
    Solution: Information technology goes into an infinite loop printing 0. The compound assignment statement 10 += 0.5 is equivalent to x = (int) (x + 0.v).
  74. What does the post-obit lawmaking fragment exercise?
    int income = Integer.parseInt(args[0]); if (income >= 311950) rate = .35; if (income >= 174700) rate = .33; if (income >= 114650) rate = .28; if (income >=  47450) rate = .25; if (income >=      0) rate = .22; Arrangement.out.println(rate);                
    It does not compile considering the compile cannot guarantee that charge per unit is initialized. Use if-else instead.
  75. Awarding of Newton's method. Write a programme 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: (one - 3r/4 + rii/8 - r3/192)2 e-r/two , where r is the radius in units of the Bohr radius (0.529173E-8 cm). Apply Newton'south method. By starting Newton'south method at different values of r, you lot tin discover all three roots. Hint: use initial values of r= 0, 5, and thirteen. Challenge: explain what happens if you utilize an initial value of r = 4 or 12.
  76. Pepys problem. In 1693, Samuel Pepys asked Isaac Newton which was more probable: getting at least one i when rolling a fair die vi times or getting at least ii 1'south when rolling a fair die 12 times. Write a plan Pepys.java that uses simulation to determine the correct answer.
  77. What is the value of the variable s after running the post-obit loop when N = i, ii, 3, 4, and five.
    Cord due south = ""; for (int i = 1; i <= North; i++) {    if (i % 2 == 0) s = due south + i + due south;    else            s = i + southward + i; }                

    Solution: Palindrome.coffee.

  78. Body mass index. The trunk mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a program BMI.coffee that takes ii control-line arguments, weight and peak, computes the BMI, and prints the respective BMI category:
    • Starvation: less than 15
    • Anorexic: less than 17.v
    • Underweight: less than 18.5
    • Platonic: greater than or equal to xviii.v but 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 40
  79. Reynolds number. The Reynolds number is the ratio if inertial forces to gluey forces and is an important 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'due south number d * 5 * rho / mu (bold all arguments are in SI units). If the Reynold's number is less than 2000, print laminar menses, if it'southward between 2000 and 4000, print transient flow, and if it's more than 4000, impress turbulent flow.
  80. Wind arctic revisited. The wind chill formula from Practice 1.2.fourteen is but valid if the current of air speed is above 3MPH and beneath 110MPH and the temperature is beneath fifty degrees Fahrenheit and to a higher place -50 degrees. Modify your solution to print an error bulletin if the user types in a value outside the allowable range.
  81. Betoken on a sphere. Write a program to print the (10, y, z) coordinates of a random signal on the surface of a sphere. Use Marsaglia' method: selection a random indicate (a, b) in the unit circle as in the do-while example. And then, set ten = 2a sqrt(1 - a^two - b^2), y = 2b sqrt(1 - a^2 - b^2), z = 1 - two(a^2 + b^2).
  82. Powers of grand. Write a programme PowersOfK.java that takes an integer K as command-line statement and prints all the positive powers of K in the Java long data type. Note: the constant Long.MAX_VALUE is the value of the largest integer in long.
  83. 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.coffee with the command-line argument 1e-50, you get 1e-50 equally the respond (instead of 1e-25); if you supply 16664444, you get an infinite loop!

  84. What happens when you try to compile the post-obit code fragment?
    double x;   if (a >= 0) ten = 3.14; if (a <  0) x = 2.71; System.out.println(x);                

    Solution: It complains that the variable ten might non have been initialized (fifty-fifty though nosotros can clearly see that x will exist initialized by i of the 2 if statements). You tin avert this problem here by using if-else.

dixonobjectioneve.blogspot.com

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

0 Response to "E Program Stops Reading Integers Once the User Enters the Same Value Three Times Consecutively"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel