Javascript required
Skip to content Skip to sidebar Skip to footer

How We Can Execute a Code Again Acording to User Choice Yes and No

1.three   Conditionals and Loops

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

If statements.

Most computations require dissimilar actions for unlike inputs.

  • The following code fragment uses an if statement to put the smaller of two int values in x and the larger of the 2 values in y, by exchanging the values in the 2 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 beneath 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 the states to execute a group of statements many times. This enables us to express lengthy computations without writing lots of lawmaking.

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

For loops.

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

  • For notation. Many loops follow the same bones scheme: initialize an index variable to some value and then use a while loop to test an get out status involving the index variable, using the last argument in the while loop to change the index variable. Coffee'south for loop is a direct way to express such loops.
    anatomy of a for loop
  • Compound assignment idioms. The idiom i++ is a autograph notation for i = i + i.
  • Scope. The scope of a variable is the function of the programme that can refer to that variable by name. Mostly the scope of a variable comprises the statements that follow the declaration in the same block 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 body.

Nesting.

The

if

,

while

, and

for

statements accept the same condition as assignment statements or any other statements in Java; that is, nosotros tin use them wherever a statement is chosen for. In particular, we tin can employ i or more of them in the torso of another statement to make compound statements. To emphasize the nesting, we apply indentation in the program code.

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

Loop examples.

examples of loops

Applications.

The ability to programme with loops and conditionals immediately opens up the earth of computation to u.s.a..

  • Ruler subdivisions. RulerN.java takes an integer command-line argument n and prints the string of ruler subdivision lengths. This program illustrates 1 of the essential characteristics of loops—the program could hardly be simpler, but it can produce a huge amount of output.
  • Harmonic numbers
  • Finite sums. The computational paradigm used in PowersOfTwo.coffee is one that you lot will utilise ofttimes. It uses two variables—ane as an alphabetize that controls a loop, and the other to accumulate a computational result. Program HarmonicNumber.coffee uses the same prototype to evaluate the sum
    $$ H_n = \frac{1}{one} + \frac{one}{2} + \frac{i}{iii} + \frac{one}{4} + \; \ldots \; + \frac{1}{due north} $$

    These numbers, which are known as the harmonic numbers, arise oftentimes in the analysis of algorithms.

  • Newton's method. Newton's method Sqrt.coffee uses a classic iterative technique known as Newton's method to compute the square root of a positive number x: Start with an estimate t. If t is equal to ten/t (up to auto precision), so t is equal to a square root of ten, so the computation is complete. If non, refine the judge by replacing t with the average of t and x/t. Each time we perform this update, nosotros become 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 equally saying that 106 = 64 + 32 + eight + 2. To compute the binary representation of due north, we consider the powers of 2 less than or equal to n in decreasing lodge to determine which vest in the binary decomposition (and therefore correspond to a i bit in the binary representation).
  • Gambler's ruin. gambler's ruin Suppose a gambler makes a series of off-white $1 bets, starting with $50, and continue to play until she either goes bankrupt or has $250. What are the chances that she will go home with $250, and how many bets might she expect to brand earlier 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 corporeality ($250), and the number of times we desire to simulate the game.
  • Prime factorization. Factors.java takes an integer control-line statement n and prints its prime factorization. In contrast to many of the other programs that we take seen (which we could do in a few minutes with a calculator or pencil and paper), this computation would not exist viable without a computer.

Other conditional and loop constructs.

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

if

,

while

, and

for

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

  • Pause statements. In some situations, we want to immediate get out a loop without letting it run to completion. Java provides the pause argument for this purpose. Prime.java takes an integer command-line argument n and prints true if n is prime, and false otherwise. There are two different ways to get out this loop: either the intermission statement is executed (considering n is not prime) or the loop-continuation condition is not satisfied (because n is prime).

    Notation that the pause statement does not apply to if or if-else statements. In a famous programming bug, the U.Due south. phone network crashed considering a programmer intended to use a break statement to go out a complicated if statement.

  • Go along statements. Java as well provides a way to skip to the next iteration of a loop: the continue statement. When a continue is executed inside the body of a for loopy, the flow of command transfers directly to the increment argument for the adjacent iteration of the loop.
  • Switch statements. The if and if-else statements allow one or two alternatives. Sometimes, a computation naturally suggests more two mutually exclusive alternatives. Coffee provides the switch statement for this purpose. NameOfDay.coffee takes an integer between 0 and half-dozen as a command-line statement and uses a switch argument to print the corresponding proper noun of the twenty-four hours (Sun to Saturday).
  • Do–while loops. A practice-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 ten and y so that (x, y) is randomly distributed inside the circumvolve centered at (0, 0) with radius 1.
    do-while loop

    With Math.random() nosotros get points that are randomly distributed in the ii-by-2 square heart at (0, 0). We simply generate points in this region until we find one that lies inside the unit disk. We always want to generate at least ane point then a practice-while loop is most appropriate. We must declare x and y outside the loop since nosotros will want to access their values later on the loop terminates.

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

  • Conditional operator. The conditional operator ?: is a ternary operator (three operands) that enables you to embed a conditional within an expression. The 3 operands are separated by the ? and : symbols. If the offset operand (a boolean expression) is true, the result has the value of the 2d expression; otherwise it has the value of the third expression.
    int min = (x < y) ? ten : y;                
  • Labeled break and continue statements. The break and continue statements apply to the innermost for or while loop. Sometimes we want to bound out of several levels of nested loops. Coffee provides the labeled break and labeled continue statements to attain this. Hither is an example.

Exercises

  1. Write a program AllEqual.java that takes three integer command-line arguments and prints equal if all iii are equal, and not equal otherwise.
  2. Write a programme RollLoadedDie.java that prints the result of rolling a loaded die such that the probability of getting a ane, 2, 3, iv, or 5 is 1/viii and the probability of getting a half-dozen is 3/eight.
  3. Rewrite TenHellos.java to make a program Hellos.java that takes the number of lines to impress as a command-line statement. You may assume that the statement is less than chiliad. Hint: consider using i % 10 and i % 100 to make up one's mind whether to apply "st", "nd", "rd", or "thursday" for press the ith Hello.
  4. Write a program FivePerLine.java that, using i for loop and one if statement, prints the integers from yard to 2000 with five integers per line. Hint: use the % operator.
  5. Write a program FunctionGrowth.coffee that prints a table of the values of ln north, n, n ln n, nii , northiii , and 2n for northward = sixteen, 32, 64, ..., 2048. Utilise tabs ('\t' characters) to line up columns.
  6. What is the value of one thousand and n afterwards executing the following code?
    int n = 123456789; int m = 0; while (n != 0) {    m = (10 * m) + (n % x);    n = due north / 10; }                
  7. What does the following lawmaking print out?
    int f = 0, g = 1; for (int i = 0; i <= 15; i++) {    System.out.println(f);    f = f + m;    g = f - g; }                
  8. Unlike the harmonic numbers, the sum ane/1 + i/4 + 1/nine + i/16 + ... + 1/n2 does converge to a constant as n grows to infinity. (Indeed, the abiding is πtwo / 6, then this formula can be used to estimate the value of π.) Which of the following for loops computes this sum? Assume that n is an int initialized to million and sum is a double initialized to 0.
    (a) for (int i = 1; i <= northward; i++)         sum = sum + i / (i * i);  (b) for (int i = i; i <= north; i++)        sum = sum + 1.0 / i * i;  (c) for (int i = 1; i <= n; i++)        sum = sum + one.0 / (i * i);  (d) for (int i = one; i <= n; i++)        sum = sum + 1 / (1.0 * i * i);                
  9. Change Binary.coffee to become a program Modify Kary.coffee that takes a second command-line argument G and converts the beginning argument to base K. Assume the base is between two and 16. For bases greater than 10, use 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 southward.

Creative Exercises

  1. Ramanujan's taxi. S. Ramanujan was an Indian mathematician who became famous for his intuition for numbers. When the English language mathematician G. H. Hardy came to visit him in the infirmary one day, Hardy remarked that the number of his taxi was 1729, a rather irksome 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 2 cubes in 2 different ways." Verify this claim by writing a program Ramanujan.java that takes an integer command-line statement n and prints all integers less than or equal to n that tin can be expressed as the sum of ii cubes in two different means - find distinct positive integers a, b, c, and d such that aiii + b3 = ciii + d3 . Use four nested for loops.

    Now, the license plate 87539319 seems similar a rather deadening number. Determine why information technology's not.

  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 exist uniquely determined from the other nine digits from the condition that d1 + 2d2 + 3d3 + ... + 10dten must be a multiple of 11 (here di denotes the ith digit from the right). The checksum digit done can be any value from 0 to 10: the ISBN convention is to use the value Ten to denote 10. Example: the checksum digit corresponding to 020131452 is v since is the just value of di betwixt 0 and and 10 for which d1 + two*2 + three*v + 4*4 + 5*ane + half dozen*3 + vii*1 + viii*0 + 9*two + ten*0 is a multiple of 11. Write a programme ISBN.java that takes a 9-digit integer equally a control-line argument, computes the checksum, and prints the 10-digit ISBN number. It's ok if you don't print any leading 0s.
  3. Exponential function. Presume that x is a positive variable of type double. Write a programme Exp.coffee that computes e^10 using the Taylor series expansion
    $$ e^ ten = i + 10 + \frac{10^2}{2!} + \frac{ten^three}{3!} + \frac{x^4}{4!} + \ldots $$
  4. Trigonometric functions. Write two programs Sin.java and Cos.java that compute sin x and cos x using the Taylor series expansions
    $$ \sin 10 = x - \frac{x^three}{iii!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \ldots $$
    $$ \cos x = 1 - \frac{x^ii}{ii!} + \frac{x^four}{iv!} - \frac{10^half-dozen}{6!} + \ldots $$
  5. Game simulation. In the game show Permit'due south Make a Deal, a contestant is presented with three doors. Behind i door is a valuable prize, behind the other two are gag gifts. Later on the contestant chooses a door, the host opens up 1 of the other two doors (never revealing the prize, of grade). The contestant is then given the opportunity to switch to the other unopened door. Should the contestant exercise so? Intuitively, it might seem that the contestant's initial choice door and the other unopened door are equally likely to contain the prize, and so at that place would be no incentive to switch. Write a program MonteHall.coffee to test this intuition past simulation. Your program should have an integer command-line argument n, play the game north times using each of the ii strategies (switch or don't switch) and impress the hazard of success for each strategy. Or you lot can 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 to the lowest degree n nth powers are needed to obtain a sum that is itself an nth power, for n > two. Write a program 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 5th power of some other positive integer. That is, find a, b, c, d, and e such that a five + b five + c five + d v = eastward 5. Use the long information type.

Spider web Exercises

  1. Write a programme RollDie.java that generates the outcome of rolling a fair half dozen-sided die (an integer betwixt 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 (one, 2, or 3) amidst a, b, and c.
  3. Write a program that takes five integer command-line arguments and prints the median (the third largest i).
  4. (hard) Now, try to compute the median of 5 elements such that when executed, it never makes more than 6 total comparisons.
  5. How can I create in an space loop with a for loop?

    Solution: for(;;) is the same every bit while(truthful).

  6. What's incorrect with the following loop?
    boolean done = false; while (done = simulated) {     ... }                
    The while loop condition uses = instead of == then information technology is an consignment statement (which makes washed ever false and the body of the loop will never be executed). It's amend to mode to avert using ==.
    boolean done = false; while (!washed) {     ... }                
  7. What's wrong with the post-obit loop that is intended to compute the sum of the integers ane through 100?
    for (int i = 1; i <= N; i++) {    int sum = 0;    sum = sum + i; } System.out.println(sum);                
    The variable sum should be defined exterior the loop. By defining it inside the loop, a new variable sum is initialized to 0 each fourth dimension through the loop; also it is non fifty-fifty accessible exterior the loop.
  8. Write a plan Hurricane.java that that takes the current of air speed (in miles per hour) every bit an integer command-line argument and prints whether it qualifies every bit a hurricane, and if so, whether it is a Category i, ii, three, 4, or five hurricane. Below is a table of the wind speeds co-ordinate to the Saffir-Simpson calibration.
    Category Current of air Speed (mph)
    i 74 - 95
    2 96 - 110
    three 111 - 130
    four 131 - 155
    v 155 and above
  9. What is wrong with the following code fragment?
    double ten = -32.2; boolean isPositive = (x > 0); if (isPositive = truthful) Organization.out.println(10 + " is positive"); else                   System.out.println(x + " is not positive");                

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

  10. Change/add one character so that the post-obit program prints twenty xs. In that location are ii unlike solutions.
    int i = 0, north = twenty; for (i = 0; i < n; i--)     System.out.print("ten");                
    Solution: Replace the i < n condition with -i < northward. Replace the i-- with northward--. ( In C, there is a tertiary: replace the < with a +.)
  11. What does the following code fragment do?
    if (ten > 0);     System.out.println("positive");                

    Solution: always prints positive regardless of the value of ten considering of the extra semicolon after the if statement.

  12. RGB to HSB converter. Write a plan RGBtoHSV.java that takes an RGB color (3 integers betwixt 0 and 255) and transforms it to an HSB color (three dissimilar integers between 0 and 255). Write a programme HSVtoRGB.java that applies the inverse transformation.
  13. Boys and girls. A couple kickoff a family decides to keep having children until they take at least one of either sex. Judge the average number of children they will have via simulation. Besides judge the most common outcome (tape the frequency counts for two, 3, and 4 children, and too for 5 and above). Assume that the probability p of having a boy or girl is ane/2.
  14. What does the following programme do?
    public static void principal(String[] args) {    int Northward = Integer.parseInt(args[0]);    int x = 1;    while (N >= one) {       Arrangement.out.println(x);       x = ii * 10;       N = N / two;    } }                
    Solution: Prints all of the powers of two less than or equal to n.
  15. Boys and girls. Repeat the previous question, but assume the couple keeps having children until they take some other child which is of the same sex as the first child. How does your respond change if p is different from 1/2?

    Surprisingly, the boilerplate number of children is ii if p = 0 or i, and 3 for all other values of p. Just the most probable 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 / ii;    a = a + a; }                

    Solution: a * b.

  17. Write a program using a loop and iv conditionals to print
    12 midnight 1am 2am ... 12 noon 1pm ... 11pm                
  18. What does the post-obit programme impress?
    public class Examination {    public static void main(String[] args) {       if (10 > 5);        else; {                      Organisation.out.println("Here");       };    }               }                
  19. Alice tosses a fair coin until she sees 2 consecutive heads. Bob tosses another fair money until he sees a head followed past a tail. Write a program to estimate the probability that Alice will make fewer tosses than Bob? Solution: 39/121.
  20. Rewrite DayOfWeek.coffee from Practise 1.ii.29 so that it prints the day of the week as Sunday, Monday, and and then forth instead of an integer betwixt 0 and 6. Use a switch statement.
  21. Number-to-English. Write a program to read in a command line integer between -999,999,999 and 999,999,999 and print the English language equivalent. Here is an exhaustive list of words that your plan should use: negative, zero, one, 2, three, four, v, six, seven, 8, nine, ten, xi, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, 30, forty, 50, sixty, lxx, 80, xc, hundred, thousand, million . Don't use hundred, when y'all tin use chiliad, e.thou., employ one grand five hundred instead of fifteen hundred. Reference.
  22. Gymnastics judging. A gymnast's score is determined by a console of six judges who each decide a score between 0.0 and 10.0. The final score is determined by discarding the high and low scores, and averaging the remaining iv. Write a program GymnasticsScorer.coffee that takes 6 existent control line inputs representing the 6 scores and prints their average, after 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), pass attempts (B), passing yards (C), touchdown passes (D), and interception (E) every bit follows:
    1. Completion ratio: W = 250/3 * ((A / B) - 0.three).
    2. Yards per laissez passer: Ten = 25/6 * ((C / B) - three).
    3. Touchdown ratio: Y = 1000/three * (D / B)
    4. Interception ratio: Z = 1250/3 * (0.095 - (E / B))
    The quarterback rating is computed by summing up the above four quantities, only rounding upwardly or down each value so that it is at to the lowest degree 0 and and at most 475/12. Write a program QuarterbackRating.coffee that takes five command line inputs A, B, C, D, and East, and prints the quarterback rating. Use your program to compute Steve Young's 1994 tape-setting season (112.8) in which he completed 324 of 461 passes for iii,969 yards, and threw 35 touchdowns and 10 interceptions. As of 2014, the all-fourth dimension single-flavour record is 122.5 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 bike. For example, 1/33 = 0.03030303.... We use the notation 0.(03) to denote that 03 repeats indefinitely. Every bit another instance, 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 in a higher place notation. Hint: employ Floyd's rule.
  25. Fri the 13th. What is the maximum number of consecutive days in which no Fri the 13th occurs? Hint: The Gregorian calendar repeats itself every 400 years (146097 days) then yous merely need to worry almost a 400 twelvemonth interval.

    Solution: 426 (e.yard., from viii/13/1999 to 10/13/2000).

  26. January 1. Is January ane more likely to fall on a Sat or Sunday? Write a programme to determine the number of times each occurs in a 400 twelvemonth interval.

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

  27. What do the following two code fragments do?
    for (int i = 0; i < N; i++)    for (int j = 0; j < Due north; j++)        if (i != j) Organization.out.println(i + ", " + j);  for (int i = 0; i < N; i++)    for (int j = 0; (i != j) && (j < N); j++)        Arrangement.out.println(i + ", " + j);                
  28. Determine what value gets printed out without using a computer. Choose the correct reply from 0, 100, 101, 517, or thou.
    int cnt = 0; for (int i = 0; i < 10; i++)    for (int j = 0; j < 10; j++)       for (int k = 0; k < x; thousand++)          if (ii*i + j >= 3*k)             cnt++; Organisation.out.println(cnt);                
  29. Rewrite CarLoan.java from Artistic Exercise XYZ and then that it properly handles an interest charge per unit of 0% and avoids dividing by 0.
  30. Write the shortest Coffee program you can that takes an integer control-line argument n and prints true if (i + 2 + ... + n) 2 is equal to (iiii + 23 + ... + northiii).

    Solution: Always print truthful.

  31. Change Sqrt.java so that it reports an fault if the user enters a negative number and works properly if the user enters zero.
  32. What happens if nosotros initialize t to -x instead of ten in plan Sqrt.coffee?
  33. Sample standard deviation of uniform distribution. Change Exercise 8 and then that information technology prints the sample standard deviation in addition to the average.
  34. Sample standard deviation of normal distribution. that takes an integer Northward as a command-line argument and uses Web Practice 1 from Department i.2 to print North standard normal random variables, and their boilerplate value, and sample standard deviation.
  35. Loaded dice. [Stephen Rudich] Suppose you take 3, three sided dice. A: {ii, six, 7}, B: { ane, 5, 9}, and C: {iii, 4, viii}. Two players roll a dice and the one with the highest value wins. Which die would you lot cull? Solution: A beats B with probability 5/nine, B beats C with probability five/9 and C beats A with probability 5/9. Be sure to cull second!
  36. Thue–Morse sequence. Write a program ThueMorse.coffee that reads in a control line integer n and prints the Thue–Morse sequence of order n. The beginning 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 effect to the cease of the previous string. The sequence has many amazing properties. For example, it is a binary sequence that is cube-complimentary: it does not contain 000, 111, 010101, or sss where s is whatsoever string. It is self-like: if you delete every other bit, yous go some other Thue–Morse sequence. Information technology arises in diverse areas of mathematics besides as chess, graphic blueprint, 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 Plan Binary2.java that is based on the following method: Write 1 if n is odd, 0 if north is fifty-fifty. Carve up n by 2, throwing abroad the remainder. Echo until north = 0 and read the answer backwards. Use % to determine whether n is even, and use string concatenation to grade the reply in reverse order.
  38. What does the following lawmaking fragment do?
    int digits = 0; practise {    digits++;    n = n / x; } while (n > 0);                

    Solution: The number of bits in the binary representation of a natural number n. We use a practise-while loop so that code output 1 if north = 0.

  39. Write a program NPerLine.java that takes an integer command-line statement north and prints the integers from 10 to 99 with n integers per line.
  40. Modify NPerLine.java and so that information technology prints the integers from 1 to thou with n integers per line. Make the integers line up past press the right number of spaces before an integer (e.g., 3 for 1-nine, ii for 10-99, and ane for 100-999).
  41. Suppose a, b, and c are random number uniformly distributed between 0 and i. What is the probability that a, b, and c class the side length of some triangle? Hint: they will course 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 iii numbers for a triangle. Hint: the three lengths will form an birdbrained triangle if and merely if (i) the sum of every two values is larger than the 3rd and (ii) the sum of the squares of every two side lengths is greater than or equal to the square of the tertiary.

    Answer.

  43. What is the value of s afterwards executing the following lawmaking?
    int One thousand = 987654321; Cord s = ""; while (M != 0) {    int digit = M % x;    south = s + digit;    K = M / 10; }                
  44. What is the value of i after the following confusing lawmaking is executed?
    int i = 10; i = i++; i = ++i; i = i++ + ++i;                

    Moral: don't write lawmaking like this.

  45. Formatted ISBN number. Write a programme ISBN2.java that reads in a nine digit integer from a control-line argument, computes the check digit, and prints the fully formatted ISBN number, e.g, 0-201-31452-five.
  46. UPC codes. The Universal Product Lawmaking (UPC) is a 12 digit lawmaking that uniquely specifies a production. The least pregnant digit done(rightmost ane) is a check digit which is the uniquely adamant by making the following expression a multiple of 10:
    (di + dthree + dfive + d7 + dix + d11) + 3 (dii + d4 + d6 + d8 + d10 + d12)

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

    (8 + 0 + 0 + 0 + v + four) + iii (2 + 1 + 0 + 0 + 8 + 0) = fifty

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

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

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

  49. Write a program Triangle.java that takes a command-line argument Northward and prints an Northward-by-N triangular pattern similar the one below.
    * * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *                
  50. Write a program Ex.java that takes a command-line argument Northward and prints a (2N + 1)-by-(2N + 1) ex like the one below. Use ii for loops and one if-else argument.
    * . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *                
  51. Write a programme BowTie.java that takes a command-line statement North and prints a (2N + 1)-by-(2N + i) bowtie similar the i below. Use two for loops and one if-else statement.
    * . . . . . *  * * . . . * *  * * * . * * *  * * * * * * *  * * * . * * *  * * . . . * *  * . . . . . *                
  52. Write a programme Diamond.java that takes a control-line argument N and prints a (2N + 1)-by-(2N + 1) diamond like the one below.
    % coffee Diamond 4 . . . . * . . . .  . . . * * * . . .  . . * * * * * . .  . * * * * * * * .  * * * * * * * * *  . * * * * * * * .  . . * * * * * . .  . . . * * * . . .  . . . . * . . . .                
  53. Write a program Heart.java that takes a command-line statement N and prints a eye.
  54. What does the programme Circumvolve.java print out when N = five?
    for (int i = -N; i <= Due north; i++) {    for (int j = -N; j <= North; j++) {       if (i*i + j*j <= N*Northward) System.out.impress("* ");       else                  Organization.out.print(". ");    }    System.out.println(); }                
  55. Seasons. Write a programme Flavour.coffee that takes two command line integers M and D and prints the season corresponding to month 1000 (1 = January, 12 = Dec) and day D in the northern hemisphere. Use the following table
    Season FROM TO
    Bound March 21 June 20
    Summer June 21 September 22
    Autumn September 23 December 21
    Winter December 21 March 20
  56. Zodiac signs. Write a programme Zodiac.java that takes two command line integers Chiliad and D and prints the Zodiac sign corresponding to month M (1 = January, 12 = December) and twenty-four hours D. Use the following table
    SIGN FROM TO
    Capricorn Dec 22 January xix
    Aquarius Jan 20 February 17
    Pisces February 18 March 19
    Aries March 20 April nineteen
    Taurus April 20 May 20
    Gemini May 21 June xx
    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 program that reads in the weight of a Muay Thai kickboxer (in pounds) equally a command-line statement and prints their weight form. Utilize 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
    Light heavyweight 167 175
    Super light heavyweight 175 183
    Cruiserweight 183 190
    Heavyweight 190 220
    Super heavyweight 220 -
  58. Euler'south sum of powers conjecture. In 1769 Euler generalized Fermat's Last Theorem and conjectured that it is impossible to notice iii 4th powers whose sum is a 4th power, or iv 5th powers whose sum is a 5th power, etc. The conjecture was disproved in 1966 by exhaustive computer search. Disprove the conjecture past finding positive integers a, b, c, d, and east such that afive + b5 + c5 + d5= e5. Write a plan Euler.java that reads in a command line parameter N and exhaustively searches for all such solutions with a, b, c, d, and east less than or equal to North. No counterexamples are known for powers greater than 5, but you can join EulerNet, a distributed computing effort to detect a counterexample for 6th powers.
  59. Blackjack. Write a program Blackjack.java that takes three command line integers x, y, and z representing your 2 blackjack cards x and y, and the dealers face-up card z, and prints the "standard strategy" for a six card deck in Atlantic city. Assume that ten, y, and z are integers between 1 and x, representing an ace through a confront card. Written report whether the histrion should hitting, stand, or split co-ordinate to these strategy tables. (When you lot acquire about arrays, you will see an alternating strategy that does not involve as many if-else statements).
  60. Blackjack with doubling. Change the previous exercise to allow doubling.
  61. Projectile movement. The following equation gives the trajectory of a ballistic missile as a function of the initial angle theta and windspeed: xxxx. Write a java program to print the (x, y) position of the missile at each time step t. Use trial and error to make up one's mind at what angle you lot should aim the missile if you promise to incinerate a target located 100 miles due east of your current location and at the same acme. Assume the windspeed is 20 mph due eastward.
  62. World series. The baseball game world series is a best of 7 competition, where the first team to win iv games wins the World Series. Suppose the stronger team has probability p > 1/2 of winning each game. Write a program to estimate the gamble that the weaker teams wins the World Series and to estimate how many games on average it will take.
  63. Consider the equation (ix/4)^ten = x^(9/4). One solution is nine/4. Tin you observe another i using Newton'southward method?
  64. Sorting networks. Write a program Sort3.java with 3 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) swap a and b if (a > c) swap 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 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 > Eastward) { t = D; D = E; Due east = 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 five integers. How many if statements does your programme apply?
  66. Optimal oblivious sorting networks. Create a plan that sorts four integers using simply 5 if statements, and ane that sorts five integers using simply 9 if statements of the type higher up? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How can you lot cheque that your programme works for all inputs?

    Solution: Sort4.java sorts 4 elements using 5 compare-exchanges. Sort5.coffee sorts v elements using nine compare-exchanges.

    The 0-i principle asserts that you 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 bank check that Sort5.java works, you only need to test it on the two^5 = 32 possible inputs of 0s and 1s.

  67. Optimal oblivious sorting (challenging). Observe an optimal sorting network for half dozen, 7, and 8 inputs, using 12, 16, and 19 if statements of the grade in the previous trouble, respectively.

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

  68. Optimal non-oblivious sorting. Write a program that sorts 5 inputs using just 7 comparisons. Hint: Offset compare the first two numbers, the second two numbers, and the larger of the two groups, and label them and then that a < b < d and c < d. Second, insert the remaining element eastward into its proper place in the chain a < b < d by first comparing confronting b, then either a or d depending on the issue. Third, insert c into the proper place in the chain involving a, b, d, and due east in the aforementioned manner that you inserted e (with the noesis that c < d). This uses 3 (offset footstep) + 2 (second step) + ii (third footstep) = 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.12t4 + 12t3 - 380tii + 4100t + 220 represents the height of a weather balloon at time t (measured in hours) for the first 48 hours subsequently its launch. Create a table of the height at time t for t = 0 to 48. What is its maximum acme? Solution: t = 5.
  70. Will the following code fragment compile? If and so, what will it do?
    int a = 10, b = eighteen; if (a = b) Arrangement.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 argument is an integer, but the compiler expects a boolean. Every bit a outcome, the program volition non 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 ane. What does the following code fragment do?
    boolean a = false; if (a = true) System.out.println("yes"); else          System.out.println("no");                
    Solution: it prints yes. Annotation that the provisional uses = instead of ==. This means that a is assigned the value true Every bit a result, the conditional expression evaluates to true. Java is not immune to the = vs. == error described in the previous exercise. For this reason, it is much improve style to use if (a) or if (!a) when testing booleans.
  72. Gotcha two. What does the post-obit lawmaking fragment practise?
    int a = 17, x = 5, y = 12; if (x > y); {    a = xiii;    x = 23; } Organisation.out.println(a);                
    Solution: Always prints xiii since in that location is a spurious semicolon subsequently the if statement. Thus, the assignment argument a = thirteen; will exist executed even though (10 <= y) It is legal (but uncommon) to have a cake that does non belong to a conditional statement, loop, or method.
  73. Gotcha 3. What does the following code fragment do?
    for (int x = 0; x < 100; x += 0.5) {     System.out.println(x); }                
    Solution: It goes into an infinite loop printing 0. The compound assignment argument x += 0.5 is equivalent to x = (int) (10 + 0.5).
  74. What does the following 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 not compile because the compile cannot guarantee that rate is initialized. Apply 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 naught. The probability is given past: (1 - 3r/four + rtwo/8 - rthree/192)2 due east-r/ii , where r is the radius in units of the Bohr radius (0.529173E-viii cm). Utilize Newton's method. By starting Newton'due south method at different values of r, you tin can observe all three roots. Hint: use initial values of r= 0, five, and 13. Claiming: explain what happens if you utilize an initial value of r = iv or 12.
  76. Pepys problem. In 1693, Samuel Pepys asked Isaac Newton which was more likely: getting at least one 1 when rolling a fair die vi times or getting at least two i'due south when rolling a fair die 12 times. Write a plan Pepys.coffee that uses simulation to decide the correct answer.
  77. What is the value of the variable due south after running the following loop when N = 1, 2, 3, four, and 5.
    String s = ""; for (int i = 1; i <= N; i++) {    if (i % 2 == 0) s = due south + i + southward;    else            s = i + s + i; }                

    Solution: Palindrome.coffee.

  78. Trunk mass alphabetize. The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the foursquare of the height (in meters). Write a plan BMI.coffee that takes two command-line arguments, weight and pinnacle, computes the BMI, and prints the corresponding BMI category:
    • Starvation: less than 15
    • Anorexic: less than 17.5
    • Underweight: less than 18.5
    • Ideal: greater than or equal to eighteen.5 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 xl
    • Morbidly Obese: greater than or equal to twoscore
  79. Reynolds number. The Reynolds number is the ratio if inertial forces to gluey 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'due south number d * v * rho / mu (assuming 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, impress transient flow, and if it's more than 4000, print turbulent flow.
  80. Current of air arctic revisited. The wind chill formula from Exercise 1.2.xiv is but valid if the air current speed is above 3MPH and below 110MPH and the temperature is below 50 degrees Fahrenheit and higher up -l degrees. Modify your solution to print an fault message if the user types in a value outside the allowable range.
  81. Point on a sphere. Write a plan to print the (x, y, z) coordinates of a random point on the surface of a sphere. Utilise Marsaglia' method: option a random point (a, b) in the unit of measurement circumvolve as in the exercise-while case. And then, gear up x = 2a sqrt(1 - a^2 - b^2), y = 2b sqrt(1 - a^2 - b^2), z = 1 - 2(a^2 + b^2).
  82. Powers of 1000. Write a plan PowersOfK.coffee that takes an integer G every bit command-line argument and prints all the positive powers of One thousand 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 instance, if you supply SqrtBug.java with the command-line argument 1e-fifty, you go 1e-50 as the answer (instead of 1e-25); if you supply 16664444, y'all get an space loop!

  84. What happens when you try to compile the post-obit lawmaking fragment?
    double x;   if (a >= 0) x = iii.14; if (a <  0) x = ii.71; Arrangement.out.println(x);                

    Solution: It complains that the variable ten might not have been initialized (even though nosotros tin clearly meet that x volition be initialized by one of the two if statements). Yous tin can avoid this trouble here by using if-else.

warbybroment.blogspot.com

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