1. Imperative programming

At its core, the virtual machine does nothing more but evaluates expressions and executes statements. The exercises in this chapter focus on the different data types, various operators, and conditional execution.

Prerequisites

  • be able to do simple screen output

  • receive user input

  • be able to distinguish between data types

  • be able to declare variables

  • know assignment and operators

  • be able to use conditional statements

  • being able to use loops for repetitions

  • be able to use nested loops

  • be able to declare and implement subroutines with methods

  • know the difference between argument and parameter

  • be able to use overloaded methods

Data types used in this chapter:

1.1. Screen output

In the first chapter, the Java program implemented a simple output. Let’s build on that and learn how to write special characters (such as quotes), set line breaks, or achieve simple formatted output.

1.1.1. Learn about the SVG specification ⭐

Graphical representations encourage us to engage in playing, which is why we want our Java programs to draw something. Java SE includes a library that allows you to open a window and draw content, but it’s not done with a few lines of code. Therefore, we want to go a different way, using SVG. The abbreviation stands for Scalable Vector Graphics, a standard for vector graphics. With SVG, we can easily describe two-dimensional graphics in text and write text from our Java programs.

Task:

1.1.2. Write an SVG circle on the console ⭐

There are several approaches for screen output in Java. Usually, the method print(…​), println(…​) or printf(…​) is used. These methods are located at the System.out object. Besides System.out there is System.err, but this is reserved for error output. Some developers also use the Console object for output, we stick with System.out.print*(…​).

Captain CiaoCiao needs a filled circle for shooting exercises, which can be printed later. For this purpose, we want to develop a new Java program.

For screen output, we can use:

System.out.print( "Text without subsequent line break" );
System.out.println( "Text followed by a newline" );
System.out.printf( "Text followed by line break%n" );
Write an SVG circle on the console

Task:

  • Create a new class SvgCircle1.

  • Create a main(…​) method so that we can run the program later.

  • Use in main(…​) the known print*(…​) methods to bring the following text to the console:

    <svg height='400' width='1000'><circle cx='100' cy='100' r='50' /></svg>
  • Enter the console output to https://tutego.de/go/trysvgcircle, and after clicking Run » you will see a circle. We want to come back to the web page whenever SVG elements are to be displayed in the following.

    W3schools svg editor circle
    Figure 1. Display an SVG output
  • Modify the program so that line breaks occur in the output. The output should be:

    <svg height='400' width='1000'>
      <circle cx='100' cy='100' r='50' />
    </svg>
  • Change the program again so that instead of single quotes, there are now double quotes in the string. The output should be:

    <svg height="400" width="1000">
     <circle cx="100" cy="100" r="50" />
    </svg>

1.2. Variables and data types

Variables store information, and variables always have a type in Java. The compiler knows at all times what kind of variable is declared, and what type of expression is in front of him.

Java has eight built-in data types: boolean, byte, char, short, int, long, float, and double. You can store numeric values and boolean values into them. The boolean values can be set to true and false. For numeric values, we have three different groups:

  • We have numeric values for Unicode characters and use the char data type for them. In addition, we have data types for general integers and floating-point numbers.

  • Integers always have signs. We have four different types of them: byte, short, int and long. The types differ according to their number of bytes, which means that the data types can hold numbers of different sizes.

  • For floating-point numbers, we have float and double available; a double has twice as many bits as a float to store.

The size of the data types is fixed in the Java specification and does not depend on the particular architecture or platform.

1.2.1. Access variables and output their assignments ⭐

Captain CiaoCiao wants to make shooting targets for novices, advanced, and professionals. The targets are of different sizes.

Our initial program defined a circle by specifying its center coordinates and radius, but we now aim to create a modifiable output by incorporating parameters.

Add from the previous task the main(…​) method.

Task:

  • Declare two int variables x, y and a double variable r in the main(…​) method.

  • Assign values to the variables.

  • Build the assignment of the variables into the output.

Example:

  • If, for example, x = 100 and y = 110 and r = 20.5, then the console output should be:

    <svg height="100" width="1000">
     <circle cx="100" cy="110" r="20.5" />
    </svg>
  • For manual assignment with x = 10, y = 10 and r = 2.686:

    <svg height="100" width="1000">
     <circle cx="10" cy="10" r="2.686" />
    </svg>

A black circle on a white background is created.

1.2.2. Generate random circles ⭐

Random numbers play a bigger role in the practice as you might think.

In Java, there is a class Math which provides important mathematical methods. Random numbers can be determined like this:

double rnd = Math.random();

The method random() is thus an offering of the Math class.

Task:

  • Refer to the Javadoc for the range of values in which the result of random() is.

  • Extend the circle program so that the radius is random, in the range including 10, but keeping it smaller than 20. Let the radius still be a floating-point number.

Example:

  • If we run the program twice, the outputs might look like this:

    <svg height="100" width="1000">
     <circle cx="100" cy="110" r="19.47493300792351" />
    </svg>
    <svg height="100" width="1000">
     <circle cx="100" cy="110" r="10.218243515543868" />
    </svg>

Alternative variants for forming random numbers in Java are:

double rnd1 = java.util.concurrent.ThreadLocalRandom.current().nextDouble();
double rnd2 = java.util.concurrent.ThreadLocalRandom.current().nextDouble(/* 0 to */ max);
double rnd3 = java.util.concurrent.ThreadLocalRandom.current().nextDouble(min, max);
int rnd4 = java.util.concurrent.ThreadLocalRandom.current().nextInt();
int rnd5 = java.util.concurrent.ThreadLocalRandom.current().nextInt(/* 0 to */max);
int rnd6 = java.util.concurrent.ThreadLocalRandom.current().nextInt(min, max);

1.2.3. Process user input ⭐

So far, we have done screen output, but have not done any input.

Using new java.util.Scanner(System.in).next*(), we can accept input from the command line. Examples:

int    number1 = new java.util.Scanner( System.in ).nextInt();
double number2 = new java.util.Scanner( System.in ).nextDouble();
String line    = new java.util.Scanner( System.in ).nextLine();

Captain CiaoCiao wants to be able to determine the position of the SVG circle itself.

Task:

  • For the circle, take the assignments for cx and cy as integers from the console, and write the generated SVG fragment back to standard output. The radius remains random.

1.3. Expressions, operands, and operators

An expression is evaluated and produces a result. Operators can be used to link operands such as literals or variables.

1.3.1. Compare numbers and money together? ⭐

Three bandits, Cosimo Fatface, Lucia Rubberneck, and Slick Foot Vito owe Bonny Brain a combined 1 million Liretta.

  1. Write a program that queries three floating-point numbers with new java.util.Scanner(System.in).nextDouble() and stores them in variables.

  2. Returns true or false if the three can raise the sum of 1 million.

1.3.2. Check if loot can be shared fairly ⭐

After a raid on the distillery, Captain CiaoCiao and his crew snatch countless bottles. Now the loot must be divided, with Captain CiaoCiao getting half (if the number of bottles is odd, he gets less than half, the captain is that generous). All other robbers should get the same share. But does this add up?

Task:

  • Write a program that reads the captured number of bottles from the command line and outputs how much Captain CiaoCiao obtains.

  • Output what is left for the crew.

  • Ask for the crew size, and see if the loot can be distributed fairly and equally so that each crew member gets the same number of bottles. An answer in the form of true or false is sufficient.

Example:

Number of bottles in total?
123000
Bottles for the captain: 61500
Bottles for all crew members: 61500
Number of crew members?
100
Fair share without remainder? true

Consider how division and remainder value relate.

1.3.3. Do two numbers share the same digit? ⭐⭐

Bonny Brain is playing anchor dominoes, which uses tiles with two squares, each containing a value from 0 to 9. She is wondering whether it’s possible to place two tiles end-to-end, even if they are rotated, so that the two squares adjacent to each other have the same values.

Task:

  1. Write a program that reads in two numbers, where the numbers are to be in the range from 0 to 99 (both limits inclusive).

  2. If the numbers are above 100, only the last two digits are to be evaluated; 100 or 200 would then be like 00 (i.e., 0), 1111 would be like 11.

  3. Test if the two numbers have a common digit.

Examples:

  • 12 and 31 have 1 as a common digit.

  • 22 and 33 do not have a common digit.

Note: The common digit is not asked, but simply an output true/false. If the number is a single digit, there is a 0 in front, so 01 and 20 have a common digit, which is 0.

1.3.4. Convert currency amount to coins ⭐⭐

In the currency Liretta, there are Liretta coins with denominations of 2 Liretta, 1 Liretta, 50 Lirettacent, 20 Lirettacent, 10 Lirettacent, 5 Lirettacent, 2 Lirettacent and 1 Lirettacent. 100 lirettacent is equal to 1 liretta.

CoinMachine

Task:

  1. Create a new class CoinMachine.

  2. The program should first ask for a floating-point number for an amount of money.

  3. Print out how the entered amount can be paid out in Literatta coins. Not all permutations are requested, but only the smallest number of coins.

Example with input 12.91 (English locale):

Please enter the amount of money:
12.91
6 x 2 Liretta
0 x 1 Liretta
1 x 50 Lirettacent
2 x 20 Lirettacent
0 x 10 Lirettacent
0 x 5 Lirettacent
0 x 2 Lirettacent
1 x 1 Lirettacent

The formatting of the output is not relevant.

The Scanner is localized, so it uses the decimal separator of the respective language when entering descendant digits.

1.3.5. One bottle of rum, 10 bottles of rum ⭐

Bonny Brain is a hunter of incorrect language, and she always makes sure that labels are grammatically correct. Many languages have specific rules for the plural. Every so often its "1 bottle" or "99 bottles", but also "0 bottles". Simplifications such as "1 bottle(s)" are typically found in user interfaces.

One bottle of rum 10 bottles of rum

Task:

  • Create a variable noOfBottles and assign a value to it greater than or equal to 0.

  • Program a grammatically correct output depending on whether there are 0, 1, or many bottles.

Example:

  • "0 bottles of rum".

  • "1 bottle of rum"

  • "99 bottles of rum"

The condition operator (?-: operator) makes the code compact.

1.4. Control flow

Conditional statements such as if-else statements are crucial imperative concepts. For the upcoming exercises involving user input validation and processing, we rely on the capability to selectively execute sections of code based on conditions.

1.4.1. Payday ⭐

Tort Ellini purchased an antique pocket watch from Bonny Brain for 1,000 Liretta and is now responsible for paying for it.

Payday

Task:

  1. Write a program that reads in the amount of money on the command line using new java.util.Scanner(System.in).nextDouble().

  2. Bonny Brain is always in a good mood, so she is happy with 10% less. She is also pleased when Tort offers 20% more. However, if Tort voluntarily pays more than 20%, Bonny Brain has the impression that something is wrong and the pocket watch probably has a valuable hidden function or holds a secret. Consider how to set up the program so that few code changes are needed when the limits shift on a whim.

  3. When Tort has the appropriate amount together, the screen displays "Good boy!"; if the amount is too low or an attempt is made to bribe, it displays "You son of a bi***!".

1.4.2. Convert liters ⭐⭐

A program should convert liquid quantities into a form that is easy for Captain CiaoCiao to read.

Task:

  • From the command line, read in a floating-point number, the order of magnitude is liters.

  • Convert the number according to the following pattern:

    • 1.0 and greater: output in liters, such as approx. 4 l for the input 4.

    • 0.1 and greater: output in centiliters, about approx. 20 cl when entering 0.2.

    • 0.001 and larger: output in milliliters, about approx. 9 ml when entering 0.009.

  • The result will always be an integer, and rounding is acceptable.

Example:

  • Conversion to ml:

    Enter quantity in liters:
    0.0124134
    approx. 12 ml
  • Conversion in cl:

    Enter quantity in liters:
    0.9876
    about 98 cl
  • Message if the value is too small:

    Enter quantity in liters:
    0.00003435
    Value too small to display
  • Input is already in liters:

    Enter quantity in liters:
    98848548485.445
    approx. 98848548485 l

1.4.3. Create SVG circles with random colors ⭐

In a previous assignment, Captain CiaoCiao called for a black circle on a white background. But there should be more colors in the mix!

Task:

  • Create a new class with a main(…​) method.

  • Output on the command line randomly, and with equal probability, red, green, blue.

  • In SVG, for circles, you can specify the color with the fill attribute, like this: <circle cx="20" cy="20" r="5" fill="blue " />. Give the circle a random color.

Example:

  • With three program starts, there could be the following screen outputs:

    <circle cx="20" cy="20" r="5" fill="green" />
    <circle cx="20" cy="20" r="5" fill="blue" />
    <circle cx="20" cy="20" r="5" fill="blue" />

1.4.4. Evaluate input strings for approval ⭐

Bonny Brain expects approval for new projects, and the approval can vary.

Task:

  • Ask for a string from the command line. We assume that the input is always lowercase.

  • If the input string is "ay", "aye", "ay, ay", "ja" or "joo", the message "Keep it up!" should be printed on the screen, all other input strings result in "Don’t you dare!".

  • Solve this exercise using the switch statement or switch expression.

1.4.5. Rewrite switch statement to switch expression ⭐

Java 14 has introduced an extended syntax for the switch statement, allowing for more concise writing of existing code.

Task:

  • Given is the following code with the classic switch statement:

    int month = new java.util.Scanner( System.in ).nextInt();
    int year = new java.util.Scanner( System.in ).nextInt();
    boolean isLeapYear =    ((year % 4 == 0) && (year % 100 != 0))
                         || (year % 400 == 0);
    
    int days;
    switch ( month ) {
      case 2:
        days = isLeapYear ? 29 : 28;
        break;
      case 4:
      case 6:
      case 9:
      case 11:
        days = 30;
        break;
      default:
        days = 31;
    }
  • Shorten the program with the switch expression.

1.5. Loops

Besides if-statements, repetitions are the second important imperative property. Java provides different language constructs for loops:

  • while loop

  • do-while loop

  • for loop

  • extended for loop

1.5.1. Create rotated SVG rectangles ⭐

After a raid, Captain CiaoCiao often comes back stressed. To relax, he colors geometric, recurring patterns. Bonny Brain is supposed to prepare sheets for him, but she dislikes doing it; a program is supposed to take care of it.

SvgRotatingRect

The following vector graphic in SVG rotates a rectangle around the center point (100, 100), by 60 degrees:

<svg height="200" width="200">
 <rect x="50" y="50" width="100" height="100" stroke="black" fill="none"
       transform="rotate(60 100 100)" />
</svg>

Task:

  • Write a program that rotates 36 SVG rectangles 10 degrees on top of each other and outputs them to the screen.

Example:

  • The output starts with:

    <svg height="200" width="200">
     <rect x="50" y="50" width="100" height="100" stroke="black"
           fill="none" transform="rotate(0 100 100)" />
     <rect x="50" y="50" width="100" height="100" stroke="black"
           fill="none" transform="rotate(10 100 100)" />
     <rect x="50" y="50" width="100" height="100" stroke="black"
           fill="none" transform="rotate(20 100 100)" />
     …
    </svg>

1.5.2. Create SVG-pearl-chain ⭐

Captain CiaoCiao wants to give a pearl necklace to his beloved Bonny Brain. This is made of three different gemstones: Sapphire (blue), Emerald (green), Spessartite Garnet (orange). He would like to have a design proposal in which the colors are randomly arranged.

BonnysPearls

The following is for an SVG document with three circles:

<svg height="100" width="1000">
 <circle cx="20" cy="20" r="5" fill="blue" />
 <circle cx="30" cy="20" r="5" fill="green" />
 <circle cx="40" cy="20" r="5" fill="orange" />
</svg>

Task:

  • Create an SVG output on the command line with 50 circles side by side.

1.5.3. Sum numbers from the command line ⭐

Captain CiaoCiao needs a program to enter a number of captured Loretta from his individual raids. This should be entered from the command line to add them up.

Sum numbers from the command line

Task:

  • Create a new class SummingCalculator.

  • Use the Scanner to input numbers until 0 is entered. Negative numbers are allowed since Captain CiaoCiao is occasionally been robbed. Ignore any potential overflows resulting from numbers that are too large.

  • After 0 is entered, the sum should be printed.

Example:

12
3
-1
0
Sum: 14

1.5.4. Go through a mathematical phenomenon ⭐

In mathematics, an iteration is a repeated calculation starting with a starting value until a certain condition is met. In calculations, iterations are an important procedure to improve the solution at each additional step after an initial approximation.

Task:

  • Declare a double variable t between 0 (inclusive) and 10 (exclusive) with the following line:

    double t = Math.random() * 10;
  • Multiply t by 2 if t < 1. However, if t >= 1, subtract 1.

  • Put this calculation into a while loop that should end when t is less than or equal to 0.

Example:

  • The output might evolve like this:

    9.835060881347246
    8.835060881347246
    7.835060881347246
    6.835060881347246
    …
    0.75
    1.5
    0.5
    1.0

1.5.5. Calculate products for faculties ⭐

For the new fleet, Rigel VII, Bonny Brain must select the lead officers; the choices are Paul Peldrion, Kate Muggle, Robinson Langdon, Lienn Langdon. However, Bonny Brain is unsure which person should take which role; there are: Commander, First Officer, Second Officer, Third Officer.

There are many possibilities of which person takes which role. How many possible arrangements of different elements there are in a row is told by the so-called permutation. A permutation without repetition is calculated by the factorial. With four persons, there are 1 × 2 × 3 × 4 = 24 possible arrangements.

The factorial of a natural number (positive integer) is formed over the product of the numbers according to the following pattern:

n! = 1 × 2 × 3 × … × (n - 1) × n

It holds that 0! = 1.

Task:

  • Write a Java program that reads a non-negative integer from the command line and displays the calculation.

Example:

  • Input: 9 → Output: 9! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 = 362880

  • Input: 3 → Output: 3! = 1 * 2 * 3 = 6

  • Input: 0 → Output: 0! = 1

  • Input: 1 → Output: 1! = 1

  • Input: -1 → Output: Number must not be negative

Use the data type long internally.

Question: From which number will there be "problems"? How do the issues show up, and how can we detect them? Can Math.multiplyExact(long x, long y) help us?

1.5.6. Determine if a number is formed by factorial ⭐

Jar Jar Dumbs has been instructed by Bonny Brain to write down all possible arrangements for a given number of people. Before looking at the list, she counts the number to determine if all permutations have been listed.

Determine if a number is formed by factorial

We saw how to calculate the factorial for a natural number in the previous assignment. But how can we find out if a number is a factorial? We know that 9! = 362880, but what about 212880 or 28?

Task:

  • Write a program that reads a natural number from the command line, and outputs whether the number is a factorial.

Example:

  • Number is factorial:

    Enter a number:
    362880
    362880 = 9!
  • Number is not a factorial:

    Enter a number:
    1000
    1000 is not a factorial

Test if the number is divisible by 2, 3, 4, 5 …

1.5.7. Find the smallest and largest digit of a number ⭐

Bonny Brain knows, of course, that decimal numbers consist of digits from 0 to 9. Since the boat ride is long and boring, she came up with a game: She gives the crew an integer, and the fastest person to name its largest and smallest digits wins one Liretta.

Find smallest largest digit number

Task:

  • Given any whole number (positive or negative), stored in a long.

  • Using a program, help find the smallest and largest digits of the stored number.

Examples:

  • 12345 → 1, 5

  • 987654 → 4, 9

  • 11111 → 1, 1

  • 0 → 0, 0

  • -23456788888234567L → 2, 8

1.5.8. A flag in the wind through nested loops ⭐

The sailors were in for a surprise when they realized that their flag had gone for a swim in the rough sea! Captain CiaoCiao, being the witty captain that he is, demanded that his crew whip up a new one ASAP. Let’s just hope it doesn’t decide to take another dip anytime soon!

flag in the wind through nested loops

Task:

  • Create the following output that looks like a small flag:

    1
    2 2
    3 3 3
    4 4 4 4
    5 5 5 5 5

Optional: The output should appear as a tree, in the sense that all lines are centered.

1.5.9. Output simple chessboard ⭐

Captain CiaoCiao is a fan of German Checkers, which is a variant of the game of checkers. He frequently takes part in competitions and has noticed that the board size can vary. Sporadically, it is 8 × 8 squares, sometimes 10 × 10 squares, he has also experienced 12 × 12 and 14 × 14.

For Captain CiaoCiao to prepare for all possible board sizes, a program should output a chessboard on the screen.

Output simple chessboard

Task:

  • Obtain from the command line the height and width of the game board.

  • Draw the board according to its given dimensions by the symbols # and _.

Example:

Checkerboard width: 10
Checkerboard height: 5
_#_#_#_#_#
#_#_#_#_#_
_#_#_#_#_#
#_#_#_#_#_
_#_#_#_#_#

1.5.10. It’s Christmastime: Displaying trees with ornaments ⭐

Christmas is coming soon, and Bonny Brain wants to print Christmas cards. For this, trees of different sizes are needed.

Its Christmastime Displaying trees with ornaments

Task:

  • Using loops, write a triangular tree top with a maximum width width on the screen.

  • In each line, the string becomes wider by 2 characters until it becomes >= width.

  • Centering is achieved by preceding spaces.

  • The leaves of the tree consist of the multiplication character *.

  • Randomly sprinkle o characters representing Christmas balls into the tree.

Example:

  • Tree with of width 7 (equal to a tree of width 8):

       *
      *o*
     ***o*
    *o*****

1.5.11. Draw fishy stitching motifs ⭐

Bonny Brain loves the sea and wants a scarf with a fish pattern. The sewing machine can stitch >< and > motifs using the symbols ><> and <><.

The following forms a pattern with a repetition of 1, so that first a fish swims to the right and then a fish swims to the left.

><> <><
Draw fishy stitching motifs

Task:

  • Write a program that, according to the assignment of a variable repetitions, first places the fish ><> repetitions times one after the other and then places the fish <>< repetitions times one after the other. The line should itself be repetitions times below the other.

Examples:

  • If repetitions is equal to 2, the output shall be:

    ><> ><> <>< <><
    ><> ><> <>< <><
  • If repetitions = 3 the program shall result in the following output:

    ><> ><> ><> <>< <>< <><
    ><> ><> ><> <>< <>< <><
    ><> ><> ><> <>< <>< <><

1.5.12. Trying instead of thinking ⭐⭐

Today’s computers are so fast to try different things at the same time. Password cracking programs work on this principle.

Captain CiaoCiao flips through the "Pirates Daily" and finds a brainteaser:

X

O

L

+

L

X

X

=

T

L

T

He has to find a digit for each of the letters L, O, T, and X to make the calculation correct. The prize for the puzzle is an old compass, which Captain CiaoCiao desperately wants to win. But unfortunately, he lacks the desire to think.

Trying instead of thinking

Task:

  • Develop a program that finds a solution by trying all possibilities.

  • Print out all the solutions and indicate which solutions have X, O, L and T all different from each other.

1.5.13. Get the number of digits of a number ⭐⭐

Bonny Brain wants to right-justify numbers. To accomplish this, spaces are placed in front of the numbers. For example, if you want the width to be 10 characters and the number is 123 (three digits), then seven spaces must be placed before the number to make the width 10.

The first step to determine the number of spaces is to determine the number of digits in a number.

Task:

  • Given is a positive integer n of type int. Output the number of digits of the number. Do not use (""+n).length(), that would be too simple …​

Examples for n and the expected output:

  • 12344

  • 31

  • 01

  • Integer.MAX_VALUE10

1.6. Methods

Methods are important because this way we can centralize common code and also give objects an API to access for clients.

1.6.1. Drawing hearts ⭐

Since Captain CiaoCiao loves his crew, there can’t be enough hearts.

Drawing hearts

Task:

  1. Create a new class LinePrinter. Put a static method line() into the class, which writes a line of ten hearts. Java can store and output the Unicode character "♥" in strings.

  2. Create a new class LinePrinterDemo that has a main(..) method and calls line().

1.6.2. Implement overloaded line methods ⭐

Next, let’s look at methods that can be passed something. Furthermore, a method name can be used multiple times: We talk about overloaded methods.

Task:

  • A method line(int len) will print a line of length len with a minus sign ("-") on the console. For example, line(3) will print --- onto the screen.

  • The method line(int len, char c) shall be callable with custom fill characters. So line(2, 'x') outputs the line xx on the screen. Can the first method use the second?

  • Add another overloaded method line(String prefix, int len, char c, String suffix) that sets a start string before the line and an end string after the line. For example, line("╠", 3, '═', "╣") returns ╠══╣. The line inside is 3 characters long, not the entire string.

Remember: you don’t have to implement all three methods completely with a loop. If you’re smart, you’ll forward from one method to the other.

Add the overloaded methods to the class LinePrinter.

Optional: Implement line(int len, String s), which sets strings next to each other, but up to the maximum length len. With s.length() you get the length of a string s and with s.charAt(int index) extract a character at the position index; the index starts at 0. Pay attention to the correct length, for example when calling

line( 5, "*=" ); // the result is *=*=*

1.6.3. Standing straight ⭐

Back in the day, the nincompoops would hoist the mast at the wrong angle. A pirate can be a bit crooked, but the mast better be straight as an arrow!

Standing straight

If you take a triangle, it can come in a variety of shapes. There are acute-angled triangles, obtuse-angled triangles, equilateral triangles, and right-angled triangles, among others. As a reminder, triangles are right-angled if c2 = a2 + b2.

Task:

  • Create a new class RightTriangle and write a new method; use the following code as a template:

    class RightTriangle {
      public static boolean isRightTriangle( double a, double b, double c ) {
        // Your implementation goes here
      }
    }
  • The method should take three sides of a triangle and return true if it is a right triangle, false otherwise.

  • Remember: each parameter a, b, c can stand for the cathetus or hypotenuse.

Example:

  • isRightTriangle(3, 4, 5)true

  • isRightTriangle(5, 4, 3)true

  • isRightTriangle(5, 12, 13)true

  • isRightTriangle(1, 2, 3)false

  • isRightTriangle(1, 1, Math.sqrt(2))false

The last example shows well that computational inaccuracy is a problem. Math.sqrt(2) * Math.sqrt(2) is (in the output) 2.00000000000004 and not exactly 2.

1.6.4. Create a multiplication table ⭐

Bonny Brain is spicing things up over at the Magical Company. She’s now selling two new products: a flamethrower for 500 Liretta and a fire extinguisher for a measly 100 Liretta.

To be able to read quickly what the price is in case of a larger purchase, a table should be created in HTML:

QuantityFlamethrowerFire extinguisher

1

500

100

2

1000

200

3

1500

300

In HTML, a table is represented as follows:

<html>
<table>
<tr><th>Quantity</th><th>Flamethrower</th></tr>
<tr><td>1</td><td>500</td></tr>
<tr><td>2</td><td>1000</td></tr>
</table>
</html>

Task:

  • On the screen, create the HTML table shown with the number 1 to 10.

  • Consider where own methods would be useful.

You can copy the generated HTML at https://jsfiddle.net/ and "run" it to see the result.

1.6.5. Cistercian numerals script ⭐⭐⭐

A numeral system is a system that consists of symbols used to represent numbers. There are different types of numeral systems that have been used in different cultures and time periods. Examples are the Roman numeral system (MCMLXXIII would be 1973) and the Arabic numeral system with the well-known numerals 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9, which is used in most parts of the world today.

The Cistercian Order is known for the Cistercian numeral system, in which the numbers from 1 to 9999 can be expressed in a single glyph. The construction plan is as follows:

Cistercian digits vertical
Figure 2. Cistercian numbers

A few examples:

Cistercian digits examples
Figure 3. examples of Cistercian numerals

Task:

  • Write a program that generates SVG on the command line for any four-digit number according to the presented pattern.

Example:

  • For 9394 the following SVG could be generated:

    <svg height="1400" width="1400">
    <g style="stroke:grey;stroke-linecap:round;stroke-width:2">
    <line x1="100" y1="85" x2="100" y2="115" />
    <line x1="100" y1="95" x2="110" y2="85" />
    <line x1="100" y1="85" x2="90" y2="85" />
    <line x1="100" y1="95" x2="90" y2="95" />
    <line x1="90" y1="85" x2="90" y2="95" />
    <line x1="100" y1="115" x2="110" y2="105" />
    <line x1="100" y1="115" x2="90" y2="115" />
    <line x1="100" y1="105" x2="90" y2="105" />
    <line x1="90" y1="115" x2="90" y2="105" />
    </g>
    </svg>
  • https://upload.wikimedia.org/wikipedia/commons/0/0b/Cistercian1-9999.png shows all possible characters.

Note the horizontal and vertical mirroring.

1.6.6. Quiz: What does Ding-Dong do? (recursion) ⭐⭐

The following method appears in a long lost program:

static long ding( long dong ) {
  return dong == 0 ? 0
                   : (dong % 10 + ding( dong / 10 ));
}

What does the method do? How could it be better named?

1.6.7. Quiz: Repdigit (Recursion) ⭐⭐

A repdigit (from repeated digits) has only identical digits.

The following Java method recursively determines whether a number is a repdigit:

static boolean isRepdigit( long n ) {
  if ( (n % 100) / 10 != n % 10 )
    return n < 10;
  return isRepdigit( n / 10 );
}

Task:

  • How does the method work?

  • The boolean expression inside the if statement

    if ( (n % 100) / 10 != n % 10 )

    can be rewritten to

    if ( n % 100 % 11 != 0 )

    Why?

1.6.8. Calculate Collatz sequence (recursion) ⭐

Lothar Collatz defined a sequence of numbers in 1937 that is now known as the Collatz sequence. It is defined as a mapping that follows a number n as follows:

  • nn/2 if n is even,

  • n → 3n + 1, if n is odd.

  • The sequence is finished when 1 is reached.

If we start, say, with n = 7, the algorithm runs through the following numbers:

  • 7 → 22 → 11 → 34 → 17 → 52 → 26 → 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

Every sequence ends with 4, 2, 1, but the reason is still an unsolved one in mathematics.

Task:

  • Create a class Collatz with a method void collatz(long n).

  • Create a main(…​) method, and compute the Collatz sequence with a starting value of 27.

  • Write a new method long collatzMax(long n), which returns the largest intermediate value reached.

  • How can we program collatz(…​) recursively so that the method returns the maximum assumed value as result? Attention, the signature must be changed! (Why?)

1.6.9. Ancient Egyptian multiplication (recursion) ⭐⭐

Computers rely heavily on arithmetic operations, which form an essential part of their tasks. Basic operations such as addition and subtraction are straightforward, and even multiplication and division by two can be easily achieved by shifting bits left and right.

In earlier processors, multiplication was not natively implemented, so software-based solutions were needed. To ensure fast performance, these solutions were limited to using only basic operations such as addition, subtraction, division by two, and multiplication by two. Interestingly, a calculation method for multiplication using these limited operations was already known to the Ancient Egyptians over 5000 years ago.

The concept is the following: a × b is equivalent to 1/1 × a × b, which is equivalent to 2/2 × a × b, which is equivalent to (a / 2) × (2 × b). Let’s test that:

4 × 3 = (4 / 2) × (3 × 2) = 2 × 6 = 12

From 4 × 3 we have come to 2 × 6. And that would be by the same rule (2 / 2) × (6 × 2) = 1 × 12 = 12. You see: When the multiplier is 1, the multiplicand has the result. (A product results from the multiplication of factors. The first factor is called a multiplier, the second multiplicand).

A second example:

multipliermultiplicand

8

7

4

14

2

28

1

56

The multiplier has reached 1 and the multiplicand contains the result with 56.

An algorithm would be quickly formulated: A loop runs as long as the multiplier is > 0. In the body of the loop, divide the multiplier by 2 and multiply the multiplicand by 2. However, there is a problem …​

The multiplier is not always an even number. If the product of 11 × 6 is to be calculated, 5.5 × 12 will, of course, give the same result, but we don’t want to work with floating-point numbers. If we calculate 11 × 6 as known, the result of integer division will be (11 / 2) × (6 × 2) = 5 × 12 = 60. The correct result is 66. We are missing 6. The multiplicand is also 6. Is this a coincidence?

Odd and even numbers are always different by one. If a is an odd number, a - 1 is an even number. If we want to calculate a × b, it is like (a - 1 + 1) × b, and expanding the product leads to (a - 1) × b + b. For example, 11 × 6 = (11 - 1 + 1) × 6 = (10 + 1) × 6 = 10 × 6 + 6 = 66. That’s right. You could continue like this and calculate 10 × 6 as well.

Let’s come back to the algorithm that divides the multiplier by two until one is reached. If a multiplier is odd, the multiplier is reduced by one so that it is even again for the next division step and a "correction value" is noted. Since there can be multiple corrections, they are all summed.

productmultiplier odd?rewrite if multiplier is oddcorrection value

22 × 3

No

11 × 6

Yes

(10 + 1) × 6 = 10 × 6 + 6

6

5 × 12

Yes

(4 + 1) × 12 = 4 × 12 + 12

12

2 × 24

No

1 × 48

Yes

(0 + 1) × 48 = 0 + 48

48

The sum of 6 + 12 + 48 is 66, and that is 22 × 3. Written in a nested way:

22 × 3 = 11 × 6 = (10 × 6) + 6 = ((4 × 12) + 12) + 6 = ((48) + 12) + 6 = 66.

Multiplying any integer would only require adding values, multiplying by 2, and dividing by 2. And it must be possible to test whether a number is even or odd.

Ancient Egyptian multiplication

Task:

  • Implement the algorithm in Java code, with and without recursion.

  • If addition costs as much as multiplication and division, how can the number of iterations be optimized?