Program Integer From 1 to X and Again

1.3   Conditionals and Loops

In the programs that nosotros have examined to this signal, each of the statements is executed one time, in the lodge given. Most programs are more complicated because the sequence of statements and the number of times each is executed tin vary. We utilize the term control menstruum to refer to statement sequencing in a program.

If statements.

Most computations require different actions for dissimilar inputs.

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

While loops.

Many computations are inherently repetitive. The

while

loop enables u.s. to execute a group of statements many times. This enables us to limited 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 World" 10 times.
  • PowersOfTwo.java takes an integer control-line argument n and prints all of the powers of ii 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 annotation. Many loops follow the same basic scheme: initialize an index variable to some value and so use a while loop to exam an exit condition involving the index variable, using the last statement in the while loop to modify the index variable. Java's for loop is a directly way to express such loops.
    anatomy of a for loop
  • Compound assignment idioms. The idiom i++ is a shorthand notation for i = i + ane.
  • Telescopic. The scope of a variable is the office of the program that can refer to that variable by proper noun. Generally the scope of a variable comprises the statements that follow the declaration in the same 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 have the aforementioned status as assignment statements or whatsoever other statements in Java; that is, we tin use them wherever a statement is chosen for. In item, we can use i or more of them in the trunk of some other statement to make compound statements. To emphasize the nesting, we apply indentation in the program lawmaking.

  • DivisorPattern.coffee has a for loop whose body contains a for loop (whose torso 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 same holds true for the columns).
  • MarginalTaxRate.java computes the marginal taxation rate for a given income. It uses several nested if-else statements to test from among a number of mutually exclusive possibilities.

Loop examples.

examples of loops

Applications.

The power to program with loops and conditionals immediately opens upward the world of ciphering to united states.

  • Ruler subdivisions. RulerN.java takes an integer command-line argument due north and prints the string of ruler subdivision lengths. This program illustrates one of the essential characteristics of loops—the programme could hardly be simpler, but it can produce a huge amount of output.
  • Harmonic numbers
  • Finite sums. The computational prototype used in PowersOfTwo.java is one that y'all will employ frequently. It uses ii variables—i as an index that controls a loop, and the other to accrue a computational upshot. Plan HarmonicNumber.java uses the aforementioned paradigm to evaluate the sum
    $$ H_n = \frac{one}{1} + \frac{i}{2} + \frac{1}{iii} + \frac{1}{four} + \; \ldots \; + \frac{one}{n} $$

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

  • Newton'south method. Newton's method Sqrt.coffee uses a archetype iterative technique known as Newton'due south method to compute the square root of a positive number x: First with an estimate t. If t is equal to x/t (up to auto precision), then t is equal to a foursquare root of x, and then the ciphering is complete. If not, refine the judge by replacing t with the average of t and x/t. Each fourth dimension we perform this update, we get closer to the desired answer.
  • Number conversion. Binary.coffee prints the binary (base 2) representation of the decimal number typed as the control-line argument. It is based on decomposing the number into a sum of powers of 2. For example, the binary representation of 106 is 1101010two, which is the same as saying that 106 = 64 + 32 + 8 + 2. To compute the binary representation of due north, we consider the powers of 2 less than or equal to n in decreasing order to determine which belong in the binary decomposition (and therefore stand for to a i bit in the binary representation).
  • Gambler'south ruin. gambler's ruin Suppose a gambler makes a serial of off-white $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 await to make earlier winning or losing? Gambler.java is a simulation that tin can assist answer these questions. It takes 3 command-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 n and prints its prime factorization. In contrast to many of the other programs that we have seen (which nosotros could practice in a few minutes with a calculator or pencil and paper), this ciphering would not exist viable without a reckoner.

Other conditional and loop constructs.

To exist consummate, 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, just information technology is worthwhile to exist aware of them.

  • Interruption statements. In some situations, we want to immediate exit a loop without letting it run to completion. Coffee provides the pause statement for this purpose. Prime.java takes an integer command-line argument north and prints true if due north is prime, and false otherwise. At that place are two different means to exit this loop: either the break statement is executed (because n is not prime number) or the loop-continuation condition is non satisfied (considering n is prime number).

    Annotation that the break argument does not apply to if or if-else statements. In a famous programming bug, the U.S. telephone network crashed because a programmer intended to apply a break argument to exit a complicated if argument.

  • Continue statements. Java also provides a mode to skip to the adjacent iteration of a loop: the go on argument. When a continue is executed within the body of a for loopy, the period of command transfers straight to the increment statement for the next iteration of the loop.
  • Switch statements. The if and if-else statements allow one or ii alternatives. Sometimes, a ciphering naturally suggests more than two mutually exclusive alternatives. Java provides the switch statement for this purpose. NameOfDay.java takes an integer between 0 and six equally a command-line statement and uses a switch statement to print the corresponding name of the day (Sunday to Saturday).
  • Do–while loops. A do-while loop is almost the same every bit a while loop except that the loop-continuation condition is omitted the first time through the loop. RandomPointInCircle.coffee sets ten and y and then that (x, y) is randomly distributed inside the circle centered at (0, 0) with radius 1.
    do-while loop

    With Math.random() we become points that are randomly distributed in the 2-past-2 square center at (0, 0). We just generate points in this region until we find one that lies inside the unit of measurement deejay. We always want to generate at least one signal so a do-while loop is most appropriate. Nosotros must declare x and y outside the loop since nosotros will desire to access their values after the loop terminates.

We don't employ the post-obit two flow command statements in this textbook, just include them here for completeness.

  • Conditional operator. The conditional operator ?: is a ternary operator (three operands) that enables you to embed a provisional within an expression. The iii operands are separated by the ? and : symbols. If the get-go operand (a boolean expression) is true, the result has the value of the second expression; otherwise information technology has the value of the tertiary expression.
    int min = (ten < y) ? x : y;                
  • Labeled break and continue statements. The break and continue statements apply to the innermost for or while loop. Sometimes nosotros want to jump out of several levels of nested loops. Java 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 control-line arguments and prints equal if all 3 are equal, and not equal otherwise.
  2. Write a program RollLoadedDie.java that prints the consequence of rolling a loaded die such that the probability of getting a ane, 2, 3, 4, or 5 is 1/8 and the probability of getting a half-dozen is three/8.
  3. Rewrite TenHellos.java to make a program Hellos.coffee that takes the number of lines to print equally a command-line argument. Y'all may assume 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 ithursday Hello.
  4. Write a program FivePerLine.coffee that, using one for loop and one if statement, prints the integers from 1000 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, north, due north ln n, northward2 , n3 , and iin for n = xvi, 32, 64, ..., 2048. Use tabs ('\t' characters) to line upward columns.
  6. What is the value of m and due north after executing the following code?
    int due north = 123456789; int g = 0; while (n != 0) {    1000 = (ten * thou) + (northward % 10);    n = n / ten; }                
  7. What does the following code impress out?
    int f = 0, g = ane; for (int i = 0; i <= 15; i++) {    System.out.println(f);    f = f + m;    g = f - g; }                
  8. Dissimilar the harmonic numbers, the sum 1/ane + 1/4 + 1/nine + 1/16 + ... + 1/n2 does converge to a constant every bit n grows to infinity. (Indeed, the constant is π2 / 6, so this formula tin can exist used to estimate the value of π.) Which of the following for loops computes this sum? Assume that n is an int initialized to meg 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 = 1; i <= north; i++)        sum = sum + 1.0 / i * i;  (c) for (int i = 1; i <= n; i++)        sum = sum + ane.0 / (i * i);  (d) for (int i = 1; i <= n; i++)        sum = sum + i / (1.0 * i * i);                
  9. Change Binary.java to get a program Alter Kary.java that takes a 2d command-line argument Chiliad and converts the start argument to base Grand. Assume the base is between two and xvi. 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 s.

Creative Exercises

  1. Ramanujan'due south taxi. South. Ramanujan was an Indian mathematician who became famous for his intuition for numbers. When the English mathematician M. H. Hardy came to visit him in the hospital one 24-hour interval, Hardy remarked that the number of his taxi was 1729, a rather dull number. To which Ramanujan replied, "No, Hardy! No, Hardy! It is a very interesting number. It is the smallest number expressible as the sum of two cubes in 2 different means." Verify this claim by writing a program Ramanujan.coffee that takes an integer control-line argument n and prints all integers less than or equal to n that tin be expressed as the sum of two cubes in two different ways - detect distinct positive integers a, b, c, and d such that a3 + b3 = c3 + d3 . Utilize iv nested for loops.

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

  2. Checksums. The International Standard Volume Number (ISBN) is a ten digit code that uniquely specifies a volume. The rightmost digit is a checksum digit which tin be uniquely determined from the other 9 digits from the condition that d1 + 2d2 + 3d3 + ... + 10d10 must be a multiple of 11 (hither di denotes the ith digit from the right). The checksum digit di can be whatsoever value from 0 to 10: the ISBN convention is to employ the value 10 to denote 10. Example: the checksum digit corresponding to 020131452 is 5 since is the only value of di between 0 and and x for which di + 2*2 + three*5 + 4*4 + five*1 + 6*3 + vii*1 + 8*0 + nine*2 + 10*0 is a multiple of 11. Write a program ISBN.coffee that takes a 9-digit integer every bit a command-line argument, computes the checksum, and prints the 10-digit ISBN number. It's ok if you don't print whatever leading 0s.
  3. Exponential office. Assume that x is a positive variable of type double. Write a plan Exp.java that computes e^x using the Taylor series expansion
    $$ due east^ ten = 1 + x + \frac{x^2}{2!} + \frac{ten^three}{3!} + \frac{x^4}{4!} + \ldots $$
  4. Trigonometric functions. Write 2 programs Sin.java and Cos.java that compute sin x and cos ten using the Taylor series expansions
    $$ \sin x = x - \frac{x^three}{3!} + \frac{ten^5}{five!} - \frac{10^vii}{7!} + \ldots $$
    $$ \cos x = one - \frac{x^2}{2!} + \frac{ten^iv}{4!} - \frac{x^half dozen}{6!} + \ldots $$
  5. Game simulation. In the game show Permit's Make a Deal, a contestant is presented with three doors. Behind one door is a valuable prize, backside the other ii are gag gifts. Later on the contestant chooses a door, the host opens up 1 of the other ii doors (never revealing the prize, of course). The contestant is and so given the opportunity to switch to the other unopened door. Should the contestant exercise so? Intuitively, information technology might seem that the contestant'due south initial option door and the other unopened door are as probable to contain the prize, and then there would be no incentive to switch. Write a program MonteHall.java to test this intuition by simulation. Your program should take an integer command-line statement north, play the game n times using each of the two strategies (switch or don't switch) and print the gamble of success for each strategy. Or you can play the game here.
  6. Euler's sum-of-powers conjecture. In 1769 Leonhard Euler formulated a generalized version of Fermat'southward Last Theorem, conjecturing that at least n northth powers are needed to obtain a sum that is itself an nth power, for northward > 2. Write a programme Euler.java to disprove Euler's conjecture (which stood until 1967), using a quintuply nested loop to find iv positive integers whose 5th power sums to the 5th ability of another positive integer. That is, find a, b, c, d, and e such that a 5 + b v + c five + d 5 = e 5. Use the long data blazon.

Web Exercises

  1. Write a program RollDie.java that generates the result of rolling a fair 6-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 singled-out values (1, two, or 3) amidst a, b, and c.
  3. Write a program that takes 5 integer command-line arguments and prints the median (the third largest one).
  4. (hard) Now, endeavour to compute the median of 5 elements such that when executed, it never makes more than than vi total comparisons.
  5. How tin I create in an infinite loop with a for loop?

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

  6. What'due south wrong with the post-obit loop?
    boolean washed = false; while (done = faux) {     ... }                
    The while loop condition uses = instead of == so it is an assignment statement (which makes washed always false and the torso of the loop volition never exist executed). It's better to style to avoid using ==.
    boolean washed = false; while (!done) {     ... }                
  7. What'due south wrong with the following loop that is intended to compute the sum of the integers 1 through 100?
    for (int i = 1; i <= Due north; 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 time through the loop; besides it is not fifty-fifty accessible outside the loop.
  8. Write a plan Hurricane.coffee that that takes the wind speed (in miles per hour) as an integer control-line statement and prints whether it qualifies as a hurricane, and if so, whether it is a Category 1, ii, three, iv, or 5 hurricane. Below is a tabular array of the wind speeds according to the Saffir-Simpson scale.
    Category Wind Speed (mph)
    1 74 - 95
    2 96 - 110
    3 111 - 130
    4 131 - 155
    v 155 and in a higher place
  9. What is incorrect with the following code fragment?
    double x = -32.2; boolean isPositive = (ten > 0); if (isPositive = true) Organization.out.println(ten + " is positive"); else                   System.out.println(x + " is not positive");                

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

  10. Modify/add together one character and then that the following plan prints 20 xs. There are two different solutions.
    int i = 0, n = 20; for (i = 0; i < n; i--)     Organisation.out.impress("x");                
    Solution: Supervene upon the i < n condition with -i < due north. Replace the i-- with n--. ( In C, there is a third: supercede the < with a +.)
  11. What does the following code fragment practise?
    if (x > 0);     System.out.println("positive");                

    Solution: ever prints positive regardless of the value of x because of the actress semicolon after the if statement.

  12. RGB to HSB converter. Write a program RGBtoHSV.java that takes an RGB colour (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 outset a family decides to keep having children until they take at least one of either sex. Estimate the average number of children they will have via simulation. Also estimate the well-nigh common outcome (record the frequency counts for 2, iii, and 4 children, and also for v and higher up). Assume that the probability p of having a boy or daughter is 1/two.
  14. What does the following program do?
    public static void primary(String[] args) {    int Due north = Integer.parseInt(args[0]);    int ten = 1;    while (N >= 1) {       System.out.println(10);       x = two * ten;       N = N / two;    } }                
    Solution: Prints all of the powers of 2 less than or equal to northward.
  15. Boys and girls. Repeat the previous question, but assume the couple keeps having children until they have another child which is of the aforementioned sex every bit the first kid. How does your answer change if p is different from 1/ii?

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

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

    Solution: a * b.

  17. Write a program using a loop and four conditionals to print
    12 midnight 1am 2am ... 12 noon 1pm ... 11pm                
  18. What does the following program impress?
    public class Exam {    public static void main(String[] args) {       if (x > 5);        else; {                      Organisation.out.println("Hither");       };    }               }                
  19. Alice tosses a off-white coin until she sees ii consecutive heads. Bob tosses another fair money until he sees a caput followed by a tail. Write a program to estimate the probability that Alice will make fewer tosses than Bob? Solution: 39/121.
  20. Rewrite DayOfWeek.java from Practice 1.two.29 so that it prints the day of the calendar week as Sunday, Monday, and so forth instead of an integer between 0 and 6. Apply a switch statement.
  21. Number-to-English. Write a plan to read in a command line integer between -999,999,999 and 999,999,999 and print the English equivalent. Hither is an exhaustive list of words that your program should use: negative, zip, one, two, three, four, five, six, seven, eight, nine, 10, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, 30, forty, 50, sixty, lxx, eighty, ninety, hundred, one thousand, million . Don't employ hundred, when you tin use thousand, e.g., use i thou 5 hundred instead of 15 hundred. Reference.
  22. Gymnastics judging. A gymnast'south score is adamant past a panel of 6 judges who each decide a score betwixt 0.0 and 10.0. The final score is determined past discarding the loftier and low scores, and averaging the remaining 4. Write a program GymnasticsScorer.java that takes 6 real command line inputs representing the 6 scores and prints their average, afterwards throwing out the 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), laissez passer attempts (B), passing yards (C), touchdown passes (D), and interception (E) as follows:
    1. Completion ratio: Due west = 250/three * ((A / B) - 0.3).
    2. Yards per pass: X = 25/half dozen * ((C / B) - 3).
    3. Touchdown ratio: Y = 1000/iii * (D / B)
    4. Interception ratio: Z = 1250/3 * (0.095 - (E / B))
    The quarterback rating is computed by summing up the above 4 quantities, but rounding up or down each value so that it is at least 0 and and at most 475/12. Write a program QuarterbackRating.java that takes five command line inputs A, B, C, D, and E, and prints the quarterback rating. Use your program to compute Steve Young's 1994 record-setting flavor (112.8) in which he completed 324 of 461 passes for three,969 yards, and threw 35 touchdowns and 10 interceptions. As of 2014, the best single-season record is 122.v by Aaron Rodgers in 2011.
  24. Decimal expansion of rational numbers. Given two integers p and q, the decimal expansion of p/q has an infinitely repeating cycle. For example, 1/33 = 0.03030303.... Nosotros apply the note 0.(03) to denote that 03 repeats indefinitely. As another instance, 8639/70000 = 0.1234(142857). Write a plan DecimalExpansion.java that reads in ii command line integers p and q and prints the decimal expansion of p/q using the above annotation. Hint: use Floyd's dominion.
  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) so you lot only need to worry about a 400 year interval.

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

  26. January 1. Is January i more probable to fall on a Sabbatum or Sunday? Write a plan to determine the number of times each occurs in a 400 yr interval.

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

  27. What do the following two code fragments do?
    for (int i = 0; i < Northward; i++)    for (int j = 0; j < Northward; j++)        if (i != j) Organisation.out.println(i + ", " + j);  for (int i = 0; i < North; i++)    for (int j = 0; (i != j) && (j < N); j++)        System.out.println(i + ", " + j);                
  28. Decide what value gets printed out without using a computer. Choose the correct answer from 0, 100, 101, 517, or 1000.
    int cnt = 0; for (int i = 0; i < 10; i++)    for (int j = 0; j < 10; j++)       for (int thou = 0; k < ten; k++)          if (2*i + j >= 3*chiliad)             cnt++; System.out.println(cnt);                
  29. Rewrite CarLoan.java from Creative Exercise XYZ and so that it properly handles an involvement rate of 0% and avoids dividing past 0.
  30. Write the shortest Java program you can that takes an integer command-line argument n and prints true if (one + 2 + ... + north) two is equal to (13 + 23 + ... + north3).

    Solution: Always impress true.

  31. Modify Sqrt.coffee so that it reports an error if the user enters a negative number and works properly if the user enters null.
  32. What happens if nosotros initialize t to -x instead of x in programme Sqrt.java?
  33. Sample standard departure of uniform distribution. Alter Do 8 so that it prints the sample standard deviation in add-on to the average.
  34. Sample standard divergence of normal distribution. that takes an integer N as a control-line argument and uses Spider web Exercise 1 from Section one.two to print N standard normal random variables, and their average value, and sample standard deviation.
  35. Loaded dice. [Stephen Rudich] Suppose you have iii, three sided die. A: {2, 6, seven}, B: { ane, 5, 9}, and C: {3, iv, 8}. 2 players roll a dice and the one with the highest value wins. Which die would yous choose? Solution: A beats B with probability v/nine, B beats C with probability five/9 and C beats A with probability 5/9. Exist sure to choose second!
  36. Thue–Morse sequence. Write a program ThueMorse.coffee that reads in a control line integer due north and prints the Thue–Morse sequence of order n. The commencement few strings are 0, 01, 0110, 01101001. Each successive string is obtained by flipping all of the bits of the previous string and concatenating the consequence to the end of the previous string. The sequence has many amazing properties. For example, it is a binary sequence that is cube-free: it does not contain 000, 111, 010101, or sss where south is whatever string. It is self-similar: if you delete every other chip, yous go another Thue–Morse sequence. It arises in various areas of mathematics as well as chess, graphic design, weaving patterns, and music composition.
  37. Plan Binary.coffee prints the binary representation of a decimal number n by casting out powers of 2. Write an alternate version Program Binary2.java 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 balance. Repeat until n = 0 and read the answer backwards. Apply % to determine whether northward is even, and use string concatenation to form the answer in opposite order.
  38. What does the post-obit code fragment do?
    int digits = 0; practise {    digits++;    n = n / 10; } while (n > 0);                

    Solution: The number of bits in the binary representation of a natural number northward. Nosotros use a do-while loop and then that lawmaking output 1 if due north = 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. Alter NPerLine.java and so that information technology prints the integers from 1 to 1000 with n integers per line. Make the integers line upward past press the right number of spaces before an integer (e.g., three for 1-nine, two for 10-99, and one for 100-999).
  41. Suppose a, b, and c are random number uniformly distributed between 0 and 1. What is the probability that a, b, and c grade 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, merely calculate the probability that the resulting triangle is birdbrained, given that the iii numbers for a triangle. Hint: the three lengths will grade an obtuse triangle if and merely if (i) the sum of every 2 values is larger than the third and (ii) the sum of the squares of every two side lengths is greater than or equal to the foursquare of the 3rd.

    Respond.

  43. What is the value of s after executing the following code?
    int Yard = 987654321; String southward = ""; while (M != 0) {    int digit = Grand % 10;    south = s + digit;    M = Thousand / x; }                
  44. What is the value of i afterwards the following disruptive code is executed?
    int i = x; i = i++; i = ++i; i = i++ + ++i;                

    Moral: don't write code like this.

  45. Formatted ISBN number. Write a program ISBN2.java that reads in a ix digit integer from a control-line statement, computes the check digit, and prints the fully formatted ISBN number, e.k, 0-201-31452-5.
  46. UPC codes. The Universal Product Code (UPC) is a 12 digit code that uniquely specifies a product. The least meaning digit d1(rightmost i) is a check digit which is the uniquely determined by making the post-obit expression a multiple of x:
    (dane + d3 + d5 + d7 + d9 + d11) + 3 (dtwo + div + d6 + d8 + d10 + d12)

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

    (8 + 0 + 0 + 0 + 5 + 4) + three (two + i + 0 + 0 + 8 + 0) = 50

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

  47. Write a program that reads in the air current speed (in knots) as a command line statement and prints its force according to the Beaufort scale. Utilise a switch statement.
  48. Making change. Write a programme that reads in a command line integer N (number of pennies) and prints the best way (fewest number of coins) to brand change using United states coins (quarters, dimes, nickels, and pennies merely). For case, if N = 73 then print
    2 quarters 2 dimes 3 pennies                

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

  49. Write a programme Triangle.java that takes a command-line argument N and prints an N-by-Due north triangular design like the 1 beneath.
    * * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *                
  50. Write a program Ex.java that takes a command-line argument N and prints a (2N + one)-by-(2N + i) ex like the i below. Use 2 for loops and one if-else argument.
    * . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *                
  51. Write a program BowTie.java that takes a command-line argument Northward and prints a (2N + 1)-by-(2N + 1) bowtie like the one beneath. Use two for loops and one if-else statement.
    * . . . . . *  * * . . . * *  * * * . * * *  * * * * * * *  * * * . * * *  * * . . . * *  * . . . . . *                
  52. Write a program Diamond.java that takes a control-line argument N and prints a (2N + ane)-past-(2N + ane) diamond like the one below.
    % coffee Diamond 4 . . . . * . . . .  . . . * * * . . .  . . * * * * * . .  . * * * * * * * .  * * * * * * * * *  . * * * * * * * .  . . * * * * * . .  . . . * * * . . .  . . . . * . . . .                
  53. Write a program Heart.java that takes a command-line argument Northward and prints a heart.
  54. What does the plan Circle.coffee print out when N = 5?
    for (int i = -N; i <= N; i++) {    for (int j = -Northward; j <= North; j++) {       if (i*i + j*j <= N*Due north) System.out.print("* ");       else                  System.out.print(". ");    }    System.out.println(); }                
  55. Seasons. Write a program Season.java that takes two control line integers M and D and prints the season corresponding to calendar month 1000 (1 = January, 12 = December) and mean solar day D in the northern hemisphere. Apply the following table
    SEASON FROM TO
    Leap March 21 June xx
    Summertime June 21 September 22
    Fall September 23 December 21
    Winter December 21 March xx
  56. Zodiac signs. Write a program Zodiac.java that takes two control line integers M and D and prints the Zodiac sign corresponding to month M (one = January, 12 = December) and day D. Use the following table
    SIGN FROM TO
    Capricorn December 22 January 19
    Aquarius January xx February 17
    Pisces February 18 March 19
    Aries March 20 April nineteen
    Taurus April 20 May xx
    Gemini May 21 June 20
    Cancer June 21 July 22
    Leo July 23 August 22
    Virgo Baronial 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) every bit a command-line argument and prints their weight course. Use a switch statement.
    Grade FROM TO
    Flyweight 0 112
    Super flyweight 112 115
    Bantamweight 115 118
    Super bantamweight 118 122
    Featherweight 122 126
    Super featherweight 126 130
    Lightweight 130 135
    Super lightweight 135 140
    Welterweight 140 147
    Super welterweight 147 154
    Middleweight 154 160
    Super middleweight 160 167
    Low-cal heavyweight 167 175
    Super calorie-free heavyweight 175 183
    Cruiserweight 183 190
    Heavyweight 190 220
    Super heavyweight 220 -
  58. Euler'southward sum of powers theorize. In 1769 Euler generalized Fermat's Last Theorem and conjectured that it is impossible to find three quaternary powers whose sum is a quaternary power, or four 5th powers whose sum is a 5th ability, etc. The theorize was disproved in 1966 by exhaustive reckoner search. Disprove the conjecture past finding positive integers a, b, c, d, and e such that a5 + bv + cfive + d5= e5. Write a program Euler.coffee that reads in a control 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, but you tin join EulerNet, a distributed calculating effort to find a counterexample for sixth powers.
  59. Blackjack. Write a program Blackjack.java that takes three command line integers x, y, and z representing your two blackjack cards x and y, and the dealers face-up card z, and prints the "standard strategy" for a 6 card deck in Atlantic city. Assume that 10, y, and z are integers between ane and x, representing an ace through a face card. Study whether the role player should hit, stand, or split according to these strategy tables. (When you learn almost arrays, you will encounter an alternate strategy that does non involve as many if-else statements).
  60. Blackjack with doubling. Modify the previous exercise to allow doubling.
  61. Projectile motion. The post-obit equation gives the trajectory of a ballistic missile as a function 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 angle y'all should aim the missile if you lot promise to incinerate a target located 100 miles e of your current location and at the same acme. Assume the windspeed is twenty mph due e.
  62. Earth serial. The baseball world series is a best of 7 contest, where the first team to win four games wins the World Series. Suppose the stronger team has probability p > 1/2 of winning each game. Write a programme to estimate the hazard that the weaker teams wins the Globe Series and to estimate how many games on boilerplate it will accept.
  63. Consider the equation (ix/4)^x = x^(nine/4). One solution is 9/iv. Can you find another one using Newton's method?
  64. Sorting networks. Write a program Sort3.java with three if statements (and no loops) that reads in three integers a, b, and c from the command line and prints them out in ascending guild.
    if (a > b) bandy a and b if (a > c) bandy a and c if (b > c) swap b and c                
  65. Oblivious sorting network. Convince yourself that the post-obit 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 > East) { t = D; D = Due east; E = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; }                
    Devise a sequence of statements that would sort 5 integers. How many if statements does your program apply?
  66. Optimal oblivious sorting networks. Create a program that sorts four integers using only five if statements, and ane that sorts v integers using only 9 if statements of the blazon above? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How can you check that your program works for all inputs?

    Solution: Sort4.java sorts 4 elements using 5 compare-exchanges. Sort5.java sorts 5 elements using 9 compare-exchanges.

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

  67. Optimal oblivious sorting (challenging). Find an optimal sorting network for vi, 7, and eight inputs, using 12, 16, and 19 if statements of the course in the previous trouble, respectively.

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

  68. Optimal not-oblivious sorting. Write a plan that sorts five inputs using but seven comparisons. Hint: Offset compare the first two numbers, the second two numbers, and the larger of the 2 groups, and label them so that a < b < d and c < d. Second, insert the remaining element e into its proper identify in the chain a < b < d past offset comparison confronting b, and then either a or d depending on the outcome. Tertiary, insert c into the proper place in the concatenation involving a, b, d, and eastward in the aforementioned mode that you inserted e (with the noesis that c < d). This uses iii (first step) + 2 (2nd step) + 2 (3rd step) = 7 comparisons. This method was outset discovered past H. B. Demuth in 1956.
  69. Weather balloon. (Etter and Ingber, p. 123) Suppose that h(t) = 0.12t4 + 12t3 - 380t2 + 4100t + 220 represents the height of a atmospheric condition balloon at time t (measured in hours) for the starting time 48 hours after its launch. Create a table of the height at time t for t = 0 to 48. What is its maximum height? Solution: t = 5.
  70. Volition the following code fragment compile? If so, what will information technology practice?
    int a = 10, b = 18; if (a = b) System.out.println("equal"); else       Organisation.out.println("not equal");                

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

  71. Gotcha 1. What does the following code fragment do?
    boolean a = false; if (a = true) System.out.println("yes"); else          Organisation.out.println("no");                
    Solution: information technology prints yes. Note that the conditional uses = instead of ==. This means that a is assigned the value true As a consequence, the conditional expression evaluates to truthful. Coffee is not allowed to the = vs. == error described in the previous exercise. For this reason, information technology is much amend style to utilize if (a) or if (!a) when testing booleans.
  72. Gotcha ii. What does the post-obit code fragment practice?
    int a = 17, x = 5, y = 12; if (x > y); {    a = 13;    10 = 23; } Arrangement.out.println(a);                
    Solution: Always prints xiii since there is a spurious semicolon after the if statement. Thus, the assignment statement a = thirteen; volition be executed even though (ten <= y) It is legal (but uncommon) to have a block that does non belong to a conditional argument, loop, or method.
  73. Gotcha 3. What does the following code fragment do?
    for (int x = 0; ten < 100; 10 += 0.5) {     Organisation.out.println(x); }                
    Solution: It goes into an space loop printing 0. The compound consignment statement x += 0.five is equivalent to ten = (int) (10 + 0.5).
  74. What does the following lawmaking fragment practice?
    int income = Integer.parseInt(args[0]); if (income >= 311950) rate = .35; if (income >= 174700) charge per unit = .33; if (income >= 114650) rate = .28; if (income >=  47450) rate = .25; if (income >=      0) charge per unit = .22; System.out.println(rate);                
    Information technology does not compile considering the compile cannot guarantee that rate is initialized. Use if-else instead.
  75. Application of Newton's method. Write a plan BohrRadius.java that finds the radii where the probability of finding the electron in the 4s excited state of hydrogen is cipher. The probability is given by: (one - 3r/four + r2/8 - r3/192)2 e-r/2 , where r is the radius in units of the Bohr radius (0.529173E-8 cm). Use Newton's method. By starting Newton'southward method at different values of r, you can notice all iii roots. Hint: apply initial values of r= 0, five, and 13. Claiming: explicate what happens if yous use an initial value of r = 4 or 12.
  76. Pepys problem. In 1693, Samuel Pepys asked Isaac Newton which was more probable: getting at to the lowest degree one 1 when rolling a fair dice vi times or getting at least two 1's when rolling a fair die 12 times. Write a plan Pepys.java that uses simulation to make up one's mind the right answer.
  77. What is the value of the variable southward after running the post-obit loop when Due north = 1, 2, 3, iv, and v.
    String south = ""; for (int i = ane; i <= North; i++) {    if (i % ii == 0) s = s + i + s;    else            s = i + southward + i; }                

    Solution: Palindrome.java.

  78. Body mass index. The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a program BMI.java that takes two control-line arguments, weight and height, computes the BMI, and prints the corresponding BMI category:
    • Starvation: less than 15
    • Anorexic: less than 17.5
    • Underweight: less than 18.5
    • Platonic: greater than or equal to 18.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 40
  79. Reynolds number. The Reynolds number is the ratio if inertial forces to viscous forces and is an important quantity in fluid dynamics. Write a programme that takes in four command-line arguments, the diameter d, the velocity v, the density rho, and the viscosity mu, and prints the Reynold's number d * v * rho / mu (assuming all arguments are in SI units). If the Reynold's number is less than 2000, impress laminar flow, if it's between 2000 and 4000, print transient flow, and if it's more 4000, print turbulent period.
  80. Wind arctic revisited. The wind arctic formula from Practise 1.two.14 is simply valid if the current of air speed is in a higher place 3MPH and beneath 110MPH and the temperature is below 50 degrees Fahrenheit and higher up -50 degrees. Modify your solution to print an mistake bulletin if the user types in a value outside the allowable range.
  81. Signal on a sphere. Write a program to impress the (x, y, z) coordinates of a random signal on the surface of a sphere. Apply Marsaglia' method: choice a random bespeak (a, b) in the unit circle as in the practise-while example. Then, gear up x = 2a sqrt(1 - a^two - b^2), y = 2b sqrt(1 - a^two - b^ii), z = 1 - 2(a^two + b^2).
  82. Powers of k. Write a programme PowersOfK.java that takes an integer Yard every bit 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 employ the loop-continuation condition (Math.abs(t*t - c) > EPSILON) in Sqrt.java instead of Math.abs(t - c/t) > t*EPSILON)?

    Solution: Surprisingly, information technology can lead to inaccurate results or worse. For example, if you supply SqrtBug.java with the command-line argument 1e-50, you lot get 1e-50 as the reply (instead of 1e-25); if y'all supply 16664444, y'all get an infinite loop!

  84. What happens when you lot endeavor to compile the following code fragment?
    double x;   if (a >= 0) x = 3.14; if (a <  0) x = two.71; System.out.println(x);                

    Solution: It complains that the variable 10 might not have been initialized (even though we can clearly encounter that ten will be initialized by one of the two if statements). You can avoid this problem here by using if-else.

sellerssheand.blogspot.com

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

0 Response to "Program Integer From 1 to X and Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel