Write a Program That Reads Three Integers and Prints Their Average
1.iii Conditionals and Loops
In the programs that we have examined to this indicate, each of the statements is executed once, in the society given. Most programs are more than complicated because the sequence of statements and the number of times each is executed can vary. Nosotros utilize the term control flow to refer to argument sequencing in a programme.
If statements.
Most computations require different actions for different inputs.
- The following code fragment uses an if statement to put the smaller of two int values in x and the larger of the two values in y, by exchanging the values in the 2 variables if necessary.
- Flip.coffee uses Math.random() and an if-else argument to print the results of a coin flip.
- The table below summarizes some typical situations where you might demand to use an if or if-else argument.
While loops.
Many computations are inherently repetitive. The
whileloop enables us 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 two that is less than or equal to a given positive integer northward.
- TenHellos.java prints "Hello World" 10 times.
- PowersOfTwo.java takes an integer command-line statement n and prints all of the powers of 2 less than or equal to northward.
For loops.
The for loop is an alternate Coffee construct that allows us even more flexibility when writing loops.
- For notation. Many loops follow the same basic scheme: initialize an index variable to some value so use a while loop to test an exit condition involving the index variable, using the last statement in the while loop to change the index variable. Java's for loop is a direct way to express such loops.
- Compound consignment idioms. The idiom i++ is a autograph notation for i = i + one.
- Scope. The scope of a variable is the role of the programme that can refer to that variable by name. Mostly the scope of a variable comprises the statements that follow the annunciation in the aforementioned block as the proclamation. For this purpose, the code in the for loop header is considered to be in the same cake equally the for loop body.
Nesting.
The
if,
while, and
forstatements have the aforementioned status every bit assignment statements or any other statements in Java; that is, nosotros tin can apply them wherever a statement is called for. In particular, we can use one or more of them in the body of another argument to make compound statements. To emphasize the nesting, we apply indentation in the program code.
- DivisorPattern.coffee has a for loop whose body contains a for loop (whose body is an if-else argument) and a impress argument. It prints a pattern of asterisks where the ith row has an asterisk in each position corresponding to divisors of i (the same holds true for the columns).
- MarginalTaxRate.coffee computes the marginal tax rate for a given income. It uses several nested if-else statements to test from amid a number of mutually exclusive possibilities.
Loop examples.
Applications.
The ability to program with loops and conditionals immediately opens up the world of computation to united states of america.
- Ruler subdivisions. RulerN.java takes an integer command-line statement n and prints the cord of ruler subdivision lengths. This plan illustrates one of the essential characteristics of loops—the program could inappreciably be simpler, but it can produce a huge amount of output.
- Finite sums. The computational epitome used in PowersOfTwo.coffee is one that y'all will use frequently. It uses two variables—ane as an index that controls a loop, and the other to accrue a computational result. Program HarmonicNumber.java uses the same paradigm to evaluate the sum
$$ H_n = \frac{1}{1} + \frac{1}{ii} + \frac{1}{3} + \frac{one}{4} + \; \ldots \; + \frac{1}{n} $$
These numbers, which are known every bit the harmonic numbers, arise often in the analysis of algorithms.
- Newton'southward method.
Sqrt.java uses a classic iterative technique known as Newton's method to compute the square root of a positive number x: Start with an guess t. If t is equal to ten/t (up to machine precision), and then t is equal to a square root of x, so the computation is complete. If not, refine the judge by replacing t with the average of t and 10/t. Each time we perform this update, we get closer to the desired respond.
- 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 1101010ii, which is the same equally maxim that 106 = 64 + 32 + 8 + 2. To compute the binary representation of n, nosotros consider the powers of 2 less than or equal to northward in decreasing social club to determine which vest in the binary decomposition (and therefore stand for to a 1 chip in the binary representation).
- Gambler's ruin.
Suppose a gambler makes a series of fair $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 make before winning or losing? Gambler.java is a simulation that tin can aid answer these questions. It takes three command-line arguments, the initial pale ($50), the goal corporeality ($250), and the number of times nosotros want to simulate the game.
- Prime factorization. Factors.coffee takes an integer command-line statement north and prints its prime number factorization. In contrast to many of the other programs that we have seen (which nosotros could do in a few minutes with a calculator or pencil and paper), this computation would non exist feasible without a estimator.

Other conditional and loop constructs.
To be complete, we consider four more than Coffee constructs related to conditionals and loops. They are used much less frequently than the
if,
while, and
forstatements that we've been working with, merely it is worthwhile to be aware of them.
- Break statements. In some situations, we desire to immediate exit a loop without letting it run to completion. Java provides the suspension statement for this purpose. Prime number.java takes an integer control-line argument northward and prints true if n is prime, and false otherwise. There are ii different ways to leave this loop: either the break statement is executed (because n is not prime) or the loop-continuation condition is non satisfied (because due north is prime).
Notation 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 use a suspension statement to exit a complicated if statement.
- Proceed statements. Java besides provides a way to skip to the next iteration of a loop: the keep statement. When a continue is executed inside the body of a for loopy, the flow of control transfers directly to the increase statement for the adjacent iteration of the loop.
- Switch statements. The if and if-else statements allow one or ii alternatives. Sometimes, a computation 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 as a command-line argument and uses a switch statement to print the respective name of the 24-hour interval (Sunday to Sabbatum).
- Do–while loops. A do-while loop is well-nigh the aforementioned as a while loop except that the loop-continuation condition is omitted the beginning time through the loop. RandomPointInCircle.java sets x and y so that (ten, y) is randomly distributed inside the circle centered at (0, 0) with radius i.
With Math.random() nosotros become points that are randomly distributed in the 2-past-2 square eye at (0, 0). We but generate points in this region until nosotros find one that lies inside the unit disk. We always want to generate at least one point so a do-while loop is most advisable. Nosotros must declare x and y outside the loop since we will desire to access their values afterward the loop terminates.
We don't use the following two flow command statements in this textbook, but include them here for completeness.
- Conditional operator. The conditional operator ?: is a ternary operator (iii operands) that enables you lot to embed a conditional within an expression. The iii operands are separated past the ? and : symbols. If the beginning operand (a boolean expression) is true, the result has the value of the second expression; otherwise it has the value of the 3rd expression.
int min = (x < y) ? ten : y;
- Labeled interruption and continue statements. The break and go on statements employ to the innermost for or while loop. Sometimes nosotros want to jump out of several levels of nested loops. Java provides the labeled suspension and labeled keep statements to accomplish this. Hither is an case.
Exercises
- Write a program AllEqual.java that takes iii integer command-line arguments and prints equal if all three are equal, and not equal otherwise.
- Write a program RollLoadedDie.coffee that prints the effect of rolling a loaded dice such that the probability of getting a 1, 2, 3, 4, or 5 is i/8 and the probability of getting a six is 3/viii.
- Rewrite TenHellos.java to brand a program Hellos.java that takes the number of lines to print as a command-line argument. You may assume that the argument is less than grand. Hint: consider using i % ten and i % 100 to make up one's mind whether to employ "st", "nd", "rd", or "th" for printing the ithursday Hello.
- Write a programme FivePerLine.java that, using ane for loop and one if statement, prints the integers from grand to 2000 with v integers per line. Hint: apply the % operator.
- Write a program FunctionGrowth.java that prints a table of the values of ln due north, n, n ln n, ntwo , nthree , and iin for due north = xvi, 32, 64, ..., 2048. Apply tabs ('\t' characters) to line up columns.
- What is the value of m and n after executing the following lawmaking?
int n = 123456789; int one thousand = 0; while (northward != 0) { m = (10 * m) + (n % 10); n = n / 10; }
- What does the following code print out?
int f = 0, g = one; for (int i = 0; i <= fifteen; i++) { System.out.println(f); f = f + g; g = f - grand; }
- Unlike the harmonic numbers, the sum 1/i + 1/4 + 1/ix + 1/xvi + ... + ane/n2 does converge to a constant as n grows to infinity. (Indeed, the abiding is π2 / six, and so this formula can be used to estimate the value of π.) Which of the post-obit for loops computes this sum? Assume that n is an int initialized to 1000000 and sum is a double initialized to 0.
(a) for (int i = ane; i <= n; i++) sum = sum + 1 / (i * i); (b) for (int i = 1; i <= n; i++) sum = sum + 1.0 / i * i; (c) for (int i = 1; i <= north; i++) sum = sum + 1.0 / (i * i); (d) for (int i = 1; i <= n; i++) sum = sum + i / (1.0 * i * i);
- Modify Binary.java to get a program Modify Kary.java that takes a second command-line argument 1000 and converts the offset argument to base K. Presume the base is between two and xvi. For bases greater than ten, use the letters A through F to stand for the 11th through 16th digits, respectively.
- Write a program code fragment that puts the binary representation of a positive integer northward into a String variable s.
Artistic Exercises
- Ramanujan'south taxi. Due south. Ramanujan was an Indian mathematician who became famous for his intuition for numbers. When the English mathematician G. H. Hardy came to visit him in the hospital one twenty-four hour period, Hardy remarked that the number of his taxi was 1729, a rather deadening number. To which Ramanujan replied, "No, Hardy! No, Hardy! It is a very interesting number. Information technology is the smallest number expressible as the sum of two cubes in ii different means." Verify this claim by writing a program Ramanujan.java that takes an integer command-line argument n and prints all integers less than or equal to n that can be expressed as the sum of ii cubes in two different ways - find distinct positive integers a, b, c, and d such that aiii + bthree = ciii + d3 . Use four nested for loops.
At present, the license plate 87539319 seems like a rather deadening number. Make up one's mind why it'south not.
- Checksums. The International Standard Volume Number (ISBN) is a 10 digit code that uniquely specifies a book. The rightmost digit is a checksum digit which tin exist uniquely determined from the other nine digits from the status that done + 2d2 + 3diii + ... + 10d10 must be a multiple of 11 (here di denotes the ith digit from the right). The checksum digit d1 can exist any value from 0 to 10: the ISBN convention is to use the value X to denote 10. Example: the checksum digit corresponding to 020131452 is 5 since is the only value of d1 between 0 and and x for which d1 + 2*2 + 3*v + 4*4 + 5*1 + 6*3 + 7*1 + eight*0 + 9*2 + 10*0 is a multiple of eleven. Write a program ISBN.java that takes a 9-digit integer as a command-line argument, computes the checksum, and prints the 10-digit ISBN number. It'southward ok if you don't print whatsoever leading 0s.
- Exponential function. Assume that x is a positive variable of blazon double. Write a plan Exp.coffee that computes east^x using the Taylor series expansion
$$ due east^ x = 1 + ten + \frac{10^ii}{2!} + \frac{x^3}{3!} + \frac{x^4}{iv!} + \ldots $$
- Trigonometric functions. Write two programs Sin.coffee and Cos.java that compute sin x and cos x using the Taylor serial expansions
$$ \sin 10 = x - \frac{x^3}{3!} + \frac{x^v}{v!} - \frac{ten^7}{seven!} + \ldots $$
$$ \cos x = ane - \frac{10^2}{2!} + \frac{x^4}{four!} - \frac{ten^half-dozen}{6!} + \ldots $$
- Game simulation. In the game prove Let's Make a Deal, a contestant is presented with three doors. Behind 1 door is a valuable prize, behind the other 2 are gag gifts. Later on the contestant chooses a door, the host opens up one of the other two doors (never revealing the prize, of course). The contestant is then given the opportunity to switch to the other unopened door. Should the contestant practice so? Intuitively, it might seem that the contestant'south initial choice door and the other unopened door are as probable to comprise the prize, so at that place would exist no incentive to switch. Write a program MonteHall.coffee to test this intuition past simulation. Your program should take an integer control-line argument north, play the game north times using each of the ii strategies (switch or don't switch) and print the chance of success for each strategy. Or yous can play the game here.
- 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 due north nth powers are needed to obtain a sum that is itself an nth power, for n > 2. Write a program Euler.java to disprove Euler's theorize (which stood until 1967), using a quintuply nested loop to discover 4 positive integers whose 5th power sums to the 5th power of another positive integer. That is, notice a, b, c, d, and e such that a 5 + b 5 + c 5 + d 5 = due east 5. Use the long information type.
Spider web Exercises
- Write a program RollDie.java that generates the result of rolling a fair six-sided dice (an integer between one and half dozen).
- Write a program that takes three integer command-line arguments a, b, and c and print the number of distinct values (1, ii, or 3) amid a, b, and c.
- Write a plan that takes five integer command-line arguments and prints the median (the third largest i).
- (hard) Now, try to compute the median of 5 elements such that when executed, it never makes more than 6 total comparisons.
- How can I create in an infinite loop with a for loop?
Solution: for(;;) is the same as while(truthful).
- What'due south wrong with the following loop?
boolean done = false; while (done = false) { ... }
boolean done = false; while (!done) { ... }
- 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 <= N; i++) { int sum = 0; sum = sum + i; } System.out.println(sum);
- Write a plan Hurricane.java that that takes the wind speed (in miles per hour) as an integer command-line argument and prints whether information technology qualifies as a hurricane, and if so, whether information technology is a Category 1, 2, 3, 4, or 5 hurricane. Beneath is a tabular array of the wind speeds according to the Saffir-Simpson scale.
Category Air current Speed (mph) 1 74 - 95 2 96 - 110 iii 111 - 130 4 131 - 155 five 155 and higher up - What is wrong with the following code fragment?
double 10 = -32.two; boolean isPositive = (x > 0); if (isPositive = true) System.out.println(x + " is positive"); else System.out.println(x + " is not positive");
Solution: It uses the assignment operator = instead of the equality operator ==. A better solution is to write if (isPositive).
- Change/add together ane character and so that the following program prints 20 xs. There are two different solutions.
int i = 0, n = twenty; for (i = 0; i < northward; i--) System.out.print("x");
- What does the following code fragment practice?
if (x > 0); System.out.println("positive");
Solution: always prints positive regardless of the value of x considering of the extra semicolon subsequently the if statement.
- RGB to HSB converter. Write a program RGBtoHSV.java that takes an RGB color (three integers between 0 and 255) and transforms it to an HSB color (three dissimilar integers betwixt 0 and 255). Write a plan HSVtoRGB.java that applies the inverse transformation.
- Boys and girls. A couple beginning a family unit decides to go on having children until they have at least i of either sexual practice. Guess the boilerplate number of children they will accept via simulation. Also estimate the most common outcome (record the frequency counts for ii, 3, and 4 children, and also for 5 and above). Assume that the probability p of having a boy or daughter is 1/2.
- What does the following program do?
public static void main(String[] args) { int Due north = Integer.parseInt(args[0]); int x = i; while (North >= 1) { Organization.out.println(ten); x = 2 * x; Due north = Northward / two; } }
- Boys and girls. Echo the previous question, only assume the couple keeps having children until they have another child which is of the aforementioned sex as the get-go child. How does your reply change if p is dissimilar from i/2?
Surprisingly, the average number of children is 2 if p = 0 or 1, and 3 for all other values of p. Simply the well-nigh likely value is 2 for all values of p.
- Given ii positive integers a and b, what result does the following code fragment get out in c
c = 0; while (b > 0) { if (b % 2 == 1) c = c + a; b = b / 2; a = a + a; }
Solution: a * b.
- Write a program using a loop and four conditionals to print
12 midnight 1am 2am ... 12 apex 1pm ... 11pm
- What does the following program print?
public class Test { public static void main(String[] args) { if (10 > v); else; { Organisation.out.println("Here"); }; } }
- Alice tosses a fair money until she sees two consecutive heads. Bob tosses another fair coin 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.
- Rewrite DayOfWeek.java from Exercise ane.ii.29 and so that information technology prints the day of the week every bit Sunday, Mon, so along instead of an integer between 0 and 6. Use a switch argument.
- Number-to-English language. Write a program to read in a control line integer between -999,999,999 and 999,999,999 and print the English equivalent. Here is an exhaustive list of words that your program should apply: negative, nix, one, two, 3, iv, 5, half dozen, seven, viii, ix, ten, 11, twelve, 13, fourteen, fifteen, sixteen, seventeen, eighteen, xix, twenty, thirty, forty, 50, sixty, seventy, eighty, ninety, hundred, 1000, million . Don't utilize hundred, when you lot can utilize thousand, e.m., use one thousand 5 hundred instead of xv hundred. Reference.
- Gymnastics judging. A gymnast's score is determined past a panel of 6 judges who each decide a score between 0.0 and x.0. The final score is determined by discarding the high and depression scores, and averaging the remaining 4. Write a plan GymnasticsScorer.java that takes half-dozen real command line inputs representing the 6 scores and prints their boilerplate, later on throwing out the high and low scores.
- Quarterback rating. To compare NFL quarterbacks, the NFL devised a the quarterback rating formula based on the quarterbacks number of completed passes (A), pass attempts (B), passing yards (C), touchdown passes (D), and interception (E) as follows:
- Completion ratio: W = 250/3 * ((A / B) - 0.3).
- Yards per laissez passer: Ten = 25/6 * ((C / B) - 3).
- Touchdown ratio: Y = 1000/3 * (D / B)
- Interception ratio: Z = 1250/3 * (0.095 - (Eastward / B))
- Decimal expansion of rational numbers. Given ii integers p and q, the decimal expansion of p/q has an infinitely repeating cycle. For example, 1/33 = 0.03030303.... We use the annotation 0.(03) to denote that 03 repeats indefinitely. As some other example, 8639/70000 = 0.1234(142857). Write a program DecimalExpansion.java that reads in two control line integers p and q and prints the decimal expansion of p/q using the above notation. Hint: use Floyd'south rule.
- Friday the 13th. What is the maximum number of sequent days in which no Friday the 13th occurs? Hint: The Gregorian calendar repeats itself every 400 years (146097 days) then you merely need to worry about a 400 year interval.
Solution: 426 (eastward.k., from eight/13/1999 to x/13/2000).
- January 1. Is January 1 more likely to fall on a Saturday or Sun? Write a program to decide the number of times each occurs in a 400 year interval.
Solution: Lord's day (58 times) is more than likely than Sabbatum (56 times).
- What exercise the following two code fragments do?
for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (i != j) System.out.println(i + ", " + j); for (int i = 0; i < North; i++) for (int j = 0; (i != j) && (j < Northward); j++) System.out.println(i + ", " + j);
- Determine what value gets printed out without using a computer. Choose the right answer from 0, 100, 101, 517, or yard.
int cnt = 0; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) for (int k = 0; k < 10; thousand++) if (2*i + j >= 3*chiliad) cnt++; Arrangement.out.println(cnt);
- Rewrite CarLoan.coffee from Creative Exercise XYZ and so that it properly handles an interest charge per unit of 0% and avoids dividing by 0.
- Write the shortest Java program you can that takes an integer command-line argument northward and prints true if (1 + two + ... + north) 2 is equal to (13 + twoiii + ... + north3).
Solution: E'er print truthful.
- Change Sqrt.java so that it reports an fault if the user enters a negative number and works properly if the user enters null.
- What happens if we initialize t to -x instead of x in program Sqrt.coffee?
- Sample standard deviation of uniform distribution. Modify Practice 8 so that information technology prints the sample standard deviation in add-on to the average.
- Sample standard deviation of normal distribution. that takes an integer N as a control-line statement and uses Web Exercise 1 from Department one.two to impress N standard normal random variables, and their average value, and sample standard deviation.
- Loaded die. [Stephen Rudich] Suppose you have three, iii sided die. A: {two, six, vii}, B: { 1, 5, nine}, and C: {three, four, eight}. Two players curlicue a die and the one with the highest value wins. Which die would you choose? Solution: A beats B with probability 5/9, B beats C with probability v/9 and C beats A with probability 5/nine. Be sure to cull second!
- Thue–Morse sequence. Write a program ThueMorse.java that reads in a command line integer n and prints the Thue–Morse sequence of order n. The first few strings are 0, 01, 0110, 01101001. Each successive string is obtained by flipping all of the bits of the previous string and concatenating the upshot to the end of the previous string. The sequence has many amazing backdrop. For example, it is a binary sequence that is cube-free: information technology does not contain 000, 111, 010101, or sss where s is any string. It is self-similar: if you delete every other scrap, you become another Thue–Morse sequence. Information technology arises in various areas of mathematics also as chess, graphic design, weaving patterns, and music composition.
- Program Binary.java prints the binary representation of a decimal number due north by casting out powers of 2. Write an alternating version Program Binary2.coffee that is based on the following method: Write ane if n is odd, 0 if n is even. Dissever n by two, throwing away the remainder. Repeat until n = 0 and read the answer backwards. Use % to determine whether n is fifty-fifty, and utilise string concatenation to form the answer in reverse order.
- What does the following lawmaking fragment practise?
int digits = 0; do { digits++; n = n / ten; } while (due north > 0);
Solution: The number of $.25 in the binary representation of a natural number n. We apply a do-while loop and so that code output ane if north = 0.
- Write a plan NPerLine.java that takes an integer command-line argument n and prints the integers from 10 to 99 with n integers per line.
- Modify NPerLine.java and then that information technology prints the integers from 1 to 1000 with north integers per line. Make the integers line up by press the right number of spaces before an integer (e.yard., three for 1-9, two for 10-99, and one for 100-999).
- Suppose a, b, and c are random number uniformly distributed betwixt 0 and one. What is the probability that a, b, and c form the side length of some triangle? Hint: they will class a triangle if and only if the sum of every two values is larger than the third.
- Repeat the previous question, but summate the probability that the resulting triangle is obtuse, given that the three numbers for a triangle. Hint: the three lengths volition form an obtuse triangle if and only if (i) the sum of every 2 values is larger than the third and (2) the sum of the squares of every two side lengths is greater than or equal to the square of the third.
Respond.
- What is the value of south after executing the following code?
int One thousand = 987654321; String s = ""; while (Thousand != 0) { int digit = Thou % x; southward = s + digit; 1000 = Yard / 10; }
- What is the value of i after the post-obit confusing code is executed?
int i = 10; i = i++; i = ++i; i = i++ + ++i;
Moral: don't write code like this.
- Formatted ISBN number. Write a program ISBN2.java that reads in a nine digit integer from a command-line statement, computes the bank check digit, and prints the fully formatted ISBN number, east.chiliad, 0-201-31452-v.
- UPC codes. The Universal Product Code (UPC) is a 12 digit code that uniquely specifies a production. The least significant digit dane(rightmost 1) is a check digit which is the uniquely determined by making the following expression a multiple of ten:
(dane + d3 + d5 + dseven + d9 + d11) + 3 (d2 + d4 + d6 + dviii + d10 + d12)
As an example, the bank check digit respective to 0-48500-00102 (Tropicana Pure Premium Orange Juice) is 8 since
(viii + 0 + 0 + 0 + 5 + 4) + 3 (2 + 1 + 0 + 0 + viii + 0) = 50
and fifty is a multiple of 10. Write a program that reads in a 11 digit integer from a command line parameter, computes the check digit, and prints the the full UPC. Hint: use a variable of type long to store the 11 digit number.
- Write a plan that reads in the wind speed (in knots) every bit a control line statement and prints its force co-ordinate to the Beaufort scale. Use a switch argument.
- Making change. Write a program that reads in a command line integer N (number of pennies) and prints the best way (fewest number of coins) to make change using The states coins (quarters, dimes, nickels, and pennies only). For example, if North = 73 then print
two quarters 2 dimes three pennies
Hint: apply the greedy algorithm. That is, dispense as many quarters as possible, then dimes, then nickels, and finally pennies.
- Write a program Triangle.coffee that takes a command-line argument Due north and prints an North-past-Due north triangular pattern like the i beneath.
* * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *
- Write a plan Ex.coffee that takes a command-line argument N and prints a (2N + 1)-by-(2N + 1) ex similar the one below. Use 2 for loops and ane if-else argument.
* . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *
- Write a program BowTie.java that takes a control-line argument North and prints a (2N + 1)-by-(2N + 1) bowtie like the one below. Use two for loops and 1 if-else statement.
* . . . . . * * * . . . * * * * * . * * * * * * * * * * * * * . * * * * * . . . * * * . . . . . *
- Write a program Diamond.coffee that takes a command-line statement N and prints a (2N + ane)-by-(2N + 1) diamond like the one beneath.
% java Diamond iv . . . . * . . . . . . . * * * . . . . . * * * * * . . . * * * * * * * . * * * * * * * * * . * * * * * * * . . . * * * * * . . . . . * * * . . . . . . . * . . . .
- Write a program Heart.java that takes a command-line argument North and prints a heart.
- What does the program Circle.coffee impress out when Due north = v?
for (int i = -North; i <= Due north; i++) { for (int j = -North; j <= N; j++) { if (i*i + j*j <= N*N) System.out.impress("* "); else Organization.out.print(". "); } Organization.out.println(); }
- Seasons. Write a plan Season.coffee that takes two command line integers Grand and D and prints the season corresponding to calendar month G (i = January, 12 = December) and twenty-four hours D in the northern hemisphere. Use the following table
SEASON FROM TO Bound March 21 June 20 Summertime June 21 September 22 Fall September 23 December 21 Wintertime Dec 21 March 20 - Zodiac signs. Write a plan Zodiac.coffee that takes two command line integers Yard and D and prints the Zodiac sign corresponding to month M (1 = January, 12 = Dec) and twenty-four hours D. Employ the following tabular array
SIGN FROM TO Capricorn Dec 22 January 19 Aquarius January 20 Feb 17 Pisces Feb 18 March nineteen Aries March 20 April 19 Taurus April 20 May 20 Gemini May 21 June 20 Cancer June 21 July 22 Leo July 23 August 22 Virgo August 23 September 22 Libra September 23 October 22 Scorpio Oct 23 Nov 21 Sagittarius November 22 Dec 21 - Muay Thai kickboxing. Write a plan that reads in the weight of a Muay Thai kickboxer (in pounds) every bit a command-line argument and prints their weight form. Use a switch statement.
Form FROM TO Flyweight 0 112 Super flyweight 112 115 Bantamweight 115 118 Super bantamweight 118 122 Featherweight 122 126 Super featherweight 126 130 Lightweight 130 135 Super lightweight 135 140 Welterweight 140 147 Super welterweight 147 154 Middleweight 154 160 Super middleweight 160 167 Light heavyweight 167 175 Super light heavyweight 175 183 Cruiserweight 183 190 Heavyweight 190 220 Super heavyweight 220 - - Euler's sum of powers conjecture. In 1769 Euler generalized Fermat's Terminal Theorem and conjectured that it is impossible to notice three 4th powers whose sum is a 4th power, or four fifth powers whose sum is a 5th ability, etc. The conjecture was disproved in 1966 by exhaustive computer search. Disprove the theorize past finding positive integers a, b, c, d, and e such that a5 + b5 + c5 + d5= due east5. Write a programme Euler.coffee that reads in a command line parameter Northward and exhaustively searches for all such solutions with a, b, c, d, and e less than or equal to North. No counterexamples are known for powers greater than five, but you can join EulerNet, a distributed computing try to notice a counterexample for sixth powers.
- Blackjack. Write a program Blackjack.java that takes three command line integers x, y, and z representing your two blackjack cards ten and y, and the dealers face-up card z, and prints the "standard strategy" for a 6 menu deck in Atlantic urban center. Assume that ten, y, and z are integers between 1 and x, representing an ace through a face bill of fare. Report whether the player should striking, stand, or split according to these strategy tables. (When y'all learn about arrays, you will encounter an alternate strategy that does not involve as many if-else statements).
- Blackjack with doubling. Alter the previous exercise to allow doubling.
- Projectile motion. The following equation gives the trajectory of a ballistic missile as a function of the initial angle theta and windspeed: xxxx. Write a java program to impress the (x, y) position of the missile at each fourth dimension step t. Employ trial and error to determine at what angle you should aim the missile if yous hope to incinerate a target located 100 miles due e of your electric current location and at the same height. Assume the windspeed is 20 mph due due east.
- World series. The baseball world series is a best of 7 competition, where the first squad to win 4 games wins the World Series. Suppose the stronger team has probability p > 1/2 of winning each game. Write a program to estimate the chance that the weaker teams wins the World Serial and to estimate how many games on average it will take.
- Consider the equation (ix/4)^x = x^(ix/4). One solution is 9/4. Can you find another one using Newton's method?
- Sorting networks. Write a program Sort3.java with three if statements (and no loops) that reads in 3 integers a, b, and c from the command line and prints them out in ascending order.
if (a > b) bandy a and b if (a > c) swap a and c if (b > c) swap b and c
- Oblivious sorting network. Convince yourself that the following lawmaking fragment rearranges the integers stored in the variables A, B, C, and D so that A <= B <= C <= D.
if (A > B) { t = A; A = B; B = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (D > E) { t = D; D = E; 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; }
- Optimal oblivious sorting networks. Create a programme that sorts four integers using only 5 if statements, and one that sorts five integers using only ix if statements of the type higher up? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How can y'all 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 information technology correctly sorts an input that is a sequence of 0s and 1s. Thus, to check that Sort5.java works, you lot only need to test it on the 2^v = 32 possible inputs of 0s and 1s.
- Optimal oblivious sorting (challenging). Detect an optimal sorting network for six, vii, and 8 inputs, using 12, xvi, and 19 if statements of the form in the previous trouble, respectively.
Solution: Sort6.java is the solution for sorting 6 elements.
- Optimal non-oblivious sorting. Write a program that sorts 5 inputs using only seven comparisons. Hint: First compare the first two numbers, the 2d ii 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 e into its proper place in the chain a < b < d by starting time comparing confronting b, then either a or d depending on the outcome. Tertiary, insert c into the proper place in the chain involving a, b, d, and east in the same fashion that you inserted eastward (with the knowledge that c < d). This uses iii (get-go stride) + ii (second step) + 2 (3rd step) = 7 comparisons. This method was showtime discovered past H. B. Demuth in 1956.
- Weather condition balloon. (Etter and Ingber, p. 123) Suppose that h(t) = 0.12t4 + 12t3 - 380t2 + 4100t + 220 represents the meridian of a weather balloon at time t (measured in hours) for the first 48 hours later its launch. Create a table of the height at time t for t = 0 to 48. What is its maximum height? Solution: t = 5.
- Will the following code fragment compile? If so, what will it exercise?
int a = 10, b = 18; if (a = b) System.out.println("equal"); else Organization.out.println("non equal");
Solution: It uses the assignment operator = instead of the equality operator == in the provisional. In Java, the result of this statement is an integer, but the compiler expects a boolean. Equally a result, the program volition not compile. In some languages (notably C and C++), this code fragment will gear up the variable a to 18 and print equal without an error.
- Gotcha 1. What does the following code fragment do?
boolean a = fake; if (a = truthful) System.out.println("yes"); else System.out.println("no");
- Gotcha 2. What does the following lawmaking fragment do?
int a = 17, x = five, y = 12; if (x > y); { a = 13; x = 23; } Arrangement.out.println(a);
- Gotcha 3. What does the following code fragment practice?
for (int x = 0; x < 100; x += 0.5) { System.out.println(x); }
0
. The compound assignment statementx += 0.5
is equivalent toten = (int) (x + 0.5)
. - What does the following code fragment do?
int income = Integer.parseInt(args[0]); if (income >= 311950) rate = .35; if (income >= 174700) rate = .33; if (income >= 114650) charge per unit = .28; if (income >= 47450) rate = .25; if (income >= 0) rate = .22; Arrangement.out.println(rate);
- Awarding of Newton'south method. Write a programme BohrRadius.java that finds the radii where the probability of finding the electron in the 4s excited state of hydrogen is zero. The probability is given by: (i - 3r/4 + rtwo/8 - r3/192)2 e-r/2 , where r is the radius in units of the Bohr radius (0.529173E-viii cm). Employ Newton's method. By starting Newton's method at different values of r, yous tin can discover all iii roots. Hint: use initial values of r= 0, 5, and 13. Challenge: explicate what happens if you employ an initial value of r = 4 or 12.
- Pepys problem. In 1693, Samuel Pepys asked Isaac Newton which was more than likely: getting at least one i when rolling a off-white die 6 times or getting at least 2 one's when rolling a fair die 12 times. Write a program Pepys.java that uses simulation to decide the right respond.
- What is the value of the variable due south after running the following loop when Due north = one, 2, 3, 4, and five.
String s = ""; for (int i = 1; i <= N; i++) { if (i % ii == 0) southward = south + i + s; else s = i + s + i; }
Solution: Palindrome.java.
- Body mass alphabetize. The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the tiptop (in meters). Write a programme BMI.java that takes two control-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 xviii.v
- Ideal: greater than or equal to 18.5 simply less than 25
- Overweight: greater than or equal to 25 just less than thirty
- Obese: greater than or equal to thirty simply less than 40
- Morbidly Obese: greater than or equal to 40
- Reynolds number. The Reynolds number is the ratio if inertial forces to sticky forces and is an important quantity in fluid dynamics. Write a programme that takes in 4 control-line arguments, the diameter d, the velocity v, the density rho, and the viscosity mu, and prints the Reynold's number d * 5 * rho / mu (bold all arguments are in SI units). If the Reynold's number is less than 2000, print laminar menstruum, if it'south betwixt 2000 and 4000, print transient flow, and if information technology'south more than 4000, print turbulent period.
- Wind chill revisited. The wind chill formula from Exercise i.2.fourteen is only valid if the wind speed is higher up 3MPH and below 110MPH and the temperature is below fifty degrees Fahrenheit and above -50 degrees. Modify your solution to impress an fault message if the user types in a value outside the allowable range.
- Point on a sphere. Write a program to impress the (x, y, z) coordinates of a random point on the surface of a sphere. Utilize Marsaglia' method: pick a random point (a, b) in the unit circumvolve every bit in the practise-while example. And then, set up x = 2a sqrt(ane - a^two - b^2), y = 2b sqrt(1 - a^2 - b^two), z = 1 - ii(a^2 + b^2).
- Powers of k. Write a programme PowersOfK.coffee that takes an integer K as control-line argument and prints all the positive powers of K in the Coffee long data blazon. Annotation: the constant Long.MAX_VALUE is the value of the largest integer in long.
- Square root, revisited. Why not use the loop-continuation condition (Math.abs(t*t - c) > EPSILON) in Sqrt.java instead of Math.abs(t - c/t) > t*EPSILON)?
Solution: Surprisingly, it can pb to inaccurate results or worse. For instance, if you supply SqrtBug.java with the command-line argument 1e-l, you become 1e-fifty as the answer (instead of 1e-25); if you supply 16664444, y'all get an infinite loop!
- What happens when yous try to compile the following code fragment?
double x; if (a >= 0) 10 = iii.14; if (a < 0) 10 = 2.71; System.out.println(x);
Solution: It complains that the variable x might not have been initialized (even though we can clearly meet that x will exist initialized past ane of the 2 if statements). Y'all can avoid this problem here by using if-else.
Source: https://introcs.cs.princeton.edu/java/13flow/
0 Response to "Write a Program That Reads Three Integers and Prints Their Average"
Post a Comment