Console

Console programs are actually even easier to write than graphics programs.  Console programs are text based and they are about interacting with our users.  Many concepts we have learned and used in the last two chapters will become clearer in this chapter and they will be set in a new context and explained in more detail.

.

Try it

Console Program

Let's have a look at a simple 'HelloWorld' console program:

async function setup() {
  createConsole();
  println('Hello World!');
}

As usual, we are only interested in the code inside the setup() function.  It basically tells the computer to display the text in quotation marks, i.e. "Hello World", in a console window.  'println' is the short form for 'print line' and means exactly that, so write a line in the console window.  Whenever we want the user to enter some information, we need to add the async keyword before the setup() function.  Console programs will not work without it. 

.

readInt()

Console programs would be quite boring if all we could do is 'println()'.  The counterpart to println is readInt().  It allows the user of our program to enter a number:

let n1 = await readInt('Enter number one: ');

The text in quotation marks is not really necessary, but it gives the users an indication of what they should do.  Here we see the await statement: it means await input from the user.  If we forget it, the program wont wait for the user.  The await and the async always go together.

.

Try it

Exercise: AddTwoIntegers

Let's take a look at an example.  We want to add two numbers and display the result on the console.

async function setup() {
  createConsole();
  println('This program adds two numbers.');
  let n1 = await readInt('Enter number one: ');
  let n2 = await readInt('Enter number two: ');
  let sum = n1 + n2;
  println( 'The sum is: ' + sum );  
}

The first line simply tells the user what the program does.  Then the user is asked to enter the first number.  The program waits until the user enters a number.  Then it prompts the user to enter the second number.  After the user has done this, we add the two numbers n1 and n2 and store the result in the variable sum.  The total is then displayed in the last line.

Question: What would a program look like that subtracts two numbers?

.

Variables

The question we ask ourselves immediately, what is a variable?  Variables are a bit like boxes into which you can put things.  What kind of things can you put in the box? For example, numbers or GRects.

Variables also have names, e.g., 'n1' or 'fritz'. We write the name on the outside of the box. For instance, if we say

let n1;

that means there's a box called 'n1'.  Next we say

n1 = 6;

This is like putting the number 6 in the box.  This is called assignment, so the box 'n1' is assigned the number '6'.  If you want, you can change the number in the box.  Then you simply make a new assignment and say

n1 = 5;

i.e., we replace the old number '6' with the new number '5'.  However, the name 'n1' has not changed, it is still written on the outside of the box.

We can not only put numbers in our boxes, but also other things.  E.g. with

let fritz;

we say that there is a box called 'fritz'.  We can put GRects into this box, so with

fritz = new GRect(50, 50);

we put a new GRect 50 pixels wide and 50 pixels high in the box. 

.

Declaration and Assignment

When we say

let n1;

we declare a variable.  The variable is called 'n1' and has no value, it is undefined.  When we say

n1 = 6;

we make an assignment, i.e. we assign the value '6' to the variable 'n1'.  So the '=' does not mean equality, but assignment.  This is very important.

As far as the names of variables are concerned, they can be almost arbitrary, they can consist of letters, numbers and the underscore.  However, some words are not allowed, such as 'if' and 'for', because they are already used by JavaScript.  Names should not start with numbers and special characters should generally be avoided.  And you always have to worry about upper and lower case!

A variable always has a name, a type and a value.

SEP: The names of variables should always be descriptive, e.g. 'blueRect'.

.

Types

What kind of types are there?  In the last chapter we already got to know some: GRect, GOval, GLine etc. are all types, more precisely data types.  But there are other types too.  The ones that will occupy us in this chapter are the simple data types.  There are about six in JavaScript, but we are only interested in the following three:

  • number:  can be integers or floating point number.
  • boolean:  used for logical values, can only have the two values true or false.
  • string:  a string can contain letters, digits, but also special characters such as '.' and '$', etc.

To see how they are used consider the following examples:

let x = 42;
let y = 42.0;
let b = true;
let z = "42";

The first two, x and y, are numbers.  The third one is a boolean.  Booleans should have the values true or false.  Notice there are no quotation marks around the true or false.  The last defines a string, you can tell by the quotation marks.  They can be single or double quotation marks, but they should match.  We will deal with the boolean data type below, the string data type we will cover in the next chapter.

.

Expression

The word expression as we use it, is used in the sense of 'mathematical expression'.  We have already seen an example, namely

let sum = n1 + n2;

On the left side of the assignment there is a variable, 'sum', and on the right side there is a mathematical expression, namely the sum of the numbers 'n1' and 'n2'.  More precisely, the sum of the numbers inside the boxes 'n1' and 'n2'.

So what this line means is: Get the numbers in the boxes 'n1' and 'n2', add them together and save the result in the box 'sum'.  You can illustrate this very nicely with the 'Jeliot' program [1].

.

Exercise: Jeliot

Jeliot is a very nice program that helps us to visualize what happens, when we execute the three lines:

int n1 = 6;
int n2 = 4;
int sum = n1 + n2;

We see our code in the code window on the left.  We can go through this code step by step.  And on the right side we see the Method Area where we also see our boxes 'n1', 'n2' and 'sum', as well as the Expression Evaluation Area.  We observe how the expression '6+4=' is currently being evaluated.  In the next step the result ('10') is put into the box 'sum'.

.

Operators

When we use the word operator, we use it in the mathematical sense, i.e. the 'plus' operator or the 'minus' operator.  In JavaScript we use the characters '+', '-', '*' and '/' to denote these operations. 

Expressions can also be a little longer:

let x = 1 + 3 * 5 / 2;

In such a case, they are usually evaluated from left to right.  Kind of in the same way you write them.  The exception, however, are multiplication and division.  You might remember from school: brackets before multiplication/division before addition/substraction.

.

Remainder

One operator we haven't talked about is the remainder operator, sometimes also called the modulo operator.  The last time we probably heard about it was in the second grade, and that was before we were able to divide properly.  If we calculated 5 / 2 at that time, then the result was: two remainder one.  Or the result of 4 / 2, was two remainder zero.  Do you still remember those times? Those were good times.

let remainder = 5 % 2;

It turns out that the remainder operator is extremely useful, so in JavaScript there is an extra sign for it, the percentage sign: '%'.  Actually, we use the remainder operator every day: if we say it is 2 pm, then we have implicitly calculated 14 % 12 in our mind.

.

Exercise: Even Numbers, Odd Numbers

A useful exercise is to list the numbers from 0 to 6 and to calculate the remainder with respect to division by 2 for each of these numbers, i.e. x % 2 We see that for even numbers the remainder is always zero and for odd numbers the remainder is always one.  This is very useful, because sometimes we want to know if a number is even or odd.

.

Try it

Exercise: AverageTwoIntegers

We have to be a little careful when doing mathematical calculations, the example AverageTwoIntegers will illustrate why.  Similar to AddTwoIntegers, we first read in two integers.  And if someone is a bit careless, he might write the following statement to calculate the average of two numbers:

let average = n1 + n2 / 2;

Interestingly, this even works, e.g. if n1=0 and n2=2.  However, for other numerical values you quickly notice that something is wrong.

Of course, the error was the missing parentheses!  What we should have written is the following:

let average = ( n1 + n2 ) / 2;

However, an even better solution is the following:

let average = ( n1 + n2 ) / 2.0;

In JavaScript it makes little difference, in other languages it does.

SEP: You should always test your code thoroughly.

.

Order of Precedence

There are many rules relating to the order of precedence in JavaScript.  The following hierarchy lists the most important ones:

  1. parentheses: ()
  2. *, /, %
  3. +, -

It says that first parentheses are evaluated, then multiplication, division and remainder, and finally addition and subtraction.  But it can get even more complicated with operators like '^', '&', '|', etc.  Therefore it is always recommended to make heavy use of parentheses.

SEP: To avoid trouble, use a lot of parentheses!

.

Constants

Some variables do not change, so they are actually constants.  For example, the circle number 'Pi' always has the value '3.1415...'.  To make a variable constant, we mark it with the keyword const:

const PI = 3.1415;

Constants cannot be changed once they have been initialized.  This may seem not very useful at first, but later we will see that using constants leads to much better code.

SEP: Constants should always be written in capital letters, e.g. 'MAX_NUM', so that they can be immediately distinguished from normal variables.

.

Try it

Exercise: Area

Write a ConsoleProgram that asks the user for the radius of a circle, then calculates its area (area = PI * radius * radius) and prints the result to the console (println()).  PI should be a constant in this program.

.

Boolean Values

So far we have dealt with the numbers.  Now let's take a look at the logical type, also called boolean.  To get a feeling for booleans, we take a look at the following inequality:

3 > 5

It is like a question:  is three greater than five?  The answer is no. One also says the statement '3 > 5' is wrong or false.  To deal with this, the data type boolean was invented:

let b = 3 > 5;
println(b);

That is, the variable b is of the data type boolean and can take the values true or false.  The whole thing should remind us a little of Karel's sensors: e.g. the beepersPresent() sensor always returned true if a beeper was there and false if none was there.

.

Conditions

Boolean expressions mostly make sense when used in a condition.  In Karel's world we used them with the if statement:

if ( beepersPresent() ) {
    pickBeeper();
} else {
    putBeeper();
}
Try it

We can do the same in a console program:

let x = readInt("Enter a number: ");
if ( x > 5 ) {
    println("Number is larger than 5.");
} else {
    println("Number is less than or equal to 5.");
}

The fact that 'x > 5' is a boolean expression is actually not really important.

SEP:  We should always use the curly braces with an if statement!

.

Comparisons

What other comparisons exist besides '>'?  Six in all:

==      equal to
!=      not equal to
>       greater than
<       less than
>=      greater than or equal to
<=      less than or equal to

In addition, JavaScript has two more comparison operators: the exactly equals '===' and the not exactly equals '!=='.  They compare not only value but also data type.  The following example shows the difference:

let x = 42;
let y = "42";
if (x == y) {
    println("x and y are equal");
}
if (x === y) {
    println("x and y are exactly equal");
}

Since x is a number and y is a string, they are equal, but not exactly equal.  In general, always use the exactly equals operators.

.

Try it

Exercise: DayOfTheWeek

Let's write a program that tells us whether a day is a weekday, a Saturday or a Sunday:

let day = await readInt("Enter day of week as int (0-6): ");
if (day == 0) {
    println("Sunday");
} else if (day <= 5) {
    println("Weekday");
} else {
    println("Saturday");
}

If the day entered is zero, it is a Sunday; otherwise, if the day is less than or equal to 5, it is a weekday; and otherwise it must be a Saturday.  This form of concatenated if statements is also known as a 'cascading if'.

.

switch Statement

Karel didn't know about the switch statement, but it is quite handy.  In principle, it does the same thing as the 'cascading if', but a little more elegantly:

let day = await readInt("Enter day of week as int (0-6): ");
switch (day) {
case 0:
    println("Sunday");
    break;
case 6:
    println("Saturday");
    break;
default:
    println("Weekday");
    break;
}

If you do not think that this looks more elegantly just wait a little.

SEP: You should always have a default in your switch statement. Also, in a cascading if there should  always be an else branch.

.

Try it

Exercise: DayOfTheWeek

We want to solve our DayOfTheWeek problem with the switch statement.  First, we use the code as above, and test if it works.  Testing means that we test many different possible inputs, even unusual ones.  (What happens if we enter -1 or 42?)

Question: What happens if we omit one of the break statements?

.

Boolean Operators

Let's remember YardstickKarel: in the last step, when Karel was collecting all the beepers to put them in a big pile, it would have been great if we could have tested two conditions at the same time:

    while ( leftIsBlocked() && beepersPresent() ) {...}

Here the '&&' means as much as 'and', so only if both conditions are fulfilled, Karel should do something. It would have been similarly practical if we had a way for Karel only to do something when something is not fulfilled,

    if ( !beepersPresent() ) {...}

Here the '!' means as much as 'not'.  Finally, we had the example of BreadcrumbKarel where Karel was supposed to do something when there was either a wall in front of him or no beeper:

    if ( frontIsBlocked() || noBeepersPresent() ) {...}

That '||' means 'or' in the sense of either-or, i.e., if either the front is blocked or there are no beepers present should Karel do something.

These three operators are the so-called boolean operators:

    !       not
    &&      and
    ||      or

The order also reflects the priority rules, so '!' has a higher priority than 'and'.

.

Truth Tables

It is common to display boolean operations in so-called truth tables.  Here b1 and b2 are the two boolean operands, and out is the boolean result, e.g.

let out = b1 && b2;

for the 'and' operation.  The truth tables for the three logical operations are as follows:

.

Exercise: LeapYear

There is a cool boolean expression that tells us whether a year is a leap year or not:

let p = ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0);

To understand the expression, it is best to write down the truth table for it.

.

Try it

while Loop

We have already met the while loop with Karel:

while ( frontIsClear() ) {
	move();
}

The while loop is executed as long as a certain condition is fulfilled.  As a simple example, let's output the numbers from 0 to 9.

let i = 0;
while (i < 10) {
    print(i + ", ");
    i = i + 1;
}

In the first line we declare a variable named i of data type int and set its value to 0. Then we test if i is less than 10.  As long as this is the case, we print the current value of i in the console window. After that we increase the value of i by one.

This last line might be a bit unusual (especially mathematicians have a problem with it).  But it is important to remember that '=' does not stand for equality, but for assignment.  So

i = i + 1;

means: take the current value of i, add one to it, and then assign the result to the variable i.

.

Exercise: CounterWithWhile

As a little exercise we will try out the counter code: simply insert the lines above into the setup() function of a console program.  What happens if we only use print() instead of println()?

.

Try it

for Loop

We got to know the for loop from the very beginning with Karel.  At that time, we were only interested in the number of times the loop is run.  But now we are ready to understand the rest.  The following for loop also outputs the numbers from 0 to 9:

for (let i = 0; i < 10; i++) {
    print(i + ", ");
}

In general, a for loop always looks like this:

for ( init; condition; step ) {
	   statements;
}

First, the init step is executed, usually something like 'int i = 0'.  Then the condition is checked, so is 'i < 10'?  If yes, the statements are executed within the loop.  Finally, step 'i++' is executed.  This is done until the condition is no longer fulfilled.

What does this 'i++' mean?  It is called the increment operator, and it means as much as the line,

i = i + 1;

So the value of the variable i is increased by one.  There is also a decrement operator that does exactly the opposite: 'i--'.

.

Exercise: For Loops with Jeliot

To understand the for loop even better, let's take a look at the for loop in Jeliot and watch step by step what happens.

.

.

for versus while

As we have seen, while loop and for loop actually do the same thing.  Thus the question arises when to use which?

  • for:  if we know from the outset how often something is done, e.g.,
    for ( let i=0; i<10; i++ ) {...}
  • while:  we use the while loop, if we don't know exactly how often a loop is executed, e.g.,
    while ( frontIsClear() ) {...} 

.

OBOB: FillRowKarel

There is another loop we haven't talked about yet, the 'Loop and a Half': it is the solution to our OBOB problem.  Let's remember FillRowKarel:

while ( frontIsClear() ) {
	putBeeper();
	move();
}
putBeeper();

The problem is that we need the 'putBeeper()' function twice.  This duplication of code occurs with every OBOB and duplicate code is always a bad thing.

SEP:  Avoid duplicate code.

.

Loop and a Half

The solution is actually quite simple and is called the 'Loop and a Half':

while ( true ) {
	putBeeper();
	if ( frontIsBlocked() ) break;
	move();
}

Let's analyze the code:  First of all, we have an infinite loop, 'while (true)'.  However, we can end this infinite loop with the break statement.  We do this when there is a wall in front of Karel, 'if ( frontIsBlocked() )''.  Now we can see why it is called 'Loop and a Half': only half of the loop is executed in the last step.  To understand the code, we should go through it step by step on a piece of paper.

.

Try it

Exercise: CashRegister

A nice application for the 'Loop and a Half' is the cash register in a grocery store: assume, we have five items in our shopping cart and we are ready to pay.  The cashier enters the prices of the individual goods, one after the other into the cash register. It adds them up and at the end outputs how much we should pay:

const SENTINEL = 0;
let total = 0;
while (true) {
    let price = await readInt("Enter price: ");
    if (price == SENTINEL)
        break;
    total += price;
}
println("Your total is: " + total);

But since not all people always buy exactly five things, we need some termination criterion: in our case it is when the cashier enters 0 for the price.  This abort criterion is sometimes also called the sentinel.

Question: Could we also use a negative number as abort criterion?

SEP:  If possible, you should not use more than one break statement.

.

Post-Increment vs Pre-Increment

So far we have only seen the increment operator as post-increment operator, but it is also available as pre-increment.  The difference is that the '++' operator is either before the variable (pre) or after (post) it.  So:

let x = 5;
let y = x++;    // Post: y=5

or

let x = 5;
let y = ++x;    // Pre: y=6

The difference is subtle, and you only notice it when this operator is related to assignments or other operations:

let a = 6;
let x = ++­­a;
let y = x++;

In the second line, first (pre) the variable a is increased by one, and then the assignment is done.  In the third line, the assignment is done first, and then (post) the variable x is incremented by one.

.

Try it

typeOf

You can ask JavaScript what the type of a given variable is with the typeof operator.  For instance, the following code,

let x = 42;
println( typeof(x) );

would output number to the console.  You may want to try the following examples to see how the typeof operator works.

let u1;
println(typeof (u1));  // undefined
let u2 = undefined;
println(typeof (u2));  // undefined
let x = 42;
println(typeof (x));   // number
let y = 42.0;
println(typeof (y));   // number
let z = "42";
println(typeof (z));   // string
let b = true;
println(typeof (b));   // boolean
let n = null;
println(typeof (n));   // object
let arr = [];
println(typeof (arr)); // object
let obj = { name: "Garfield", age: 42 };
println(typeof (obj)); // object
let f = function () { };
println(typeof (f));   // function

The last four types you have not seen, they will come soon.

.


Review

We have made it!  This chapter was a little more difficult than the previous two.  But from now on it's all downhill.  What have we learned in this chapter?  We have

  • got to know variables,
  • reminded us of the remainder operator,
  • had our first contact with constants,
  • seen boolean operators and truth tables for the first time,
  • found that the if and switch statements are very similar,
  • learned when we should use a for and when a while loop and
  • found the solution to our OBOB problem with the 'Loop and a Half'.

The most important thing in this chapter however was that we filled all the little details we left unexplained in the first two chapters.

.


Projects

The following projects may not be as interesting as those in the last chapter.  But they are the basis for future chapters.

.

Try it

Countdown

Karel loves rockets and especially the countdown just before lift-off.  Therefore we want to write a program that displays the numbers from 10 to 0 on the console.

.

.

.

.

Try it

Calculator

The DoubleBeeper was a lot of work for Karel.  This is much easier with console programs and variables.  That's why we want to write a console program that adds two numbers.

What is a bit annoying about the program, that we have to restart it every time we want to make a new addition.  What could be done to allow the program to allow multiple additions (always of two numbers)?

.

Try it

Temperature

Karel loves Europe, but he can't deal with those Celsius.  That's why we write a program for him that converts Fahrenheit to Celsius.  We ask the user to give us a temperature in Fahrenheit.  Using readInt() we store them in the variable f. And with the formula

let c = (5.0 / 9.0) * (f - 32);

we can convert it to Celsius.

What happens if you enter 33 for the Fahrenheit?  The result is: 0.5555555555555556.  If you  rather want rounded results, you can use the function Math.round() to do that:

let c = Math.round( (5.0 / 9.0) * (f - 32) );

We will also need the function Math.trunc(): it truncates, that rounds off the result.  Both can be used to convert floating point numbers to integers.

.

Try it

Squares

As an example for the use of constants, we want to write a console program that outputs the square numbers of the numbers from 0 to MAX_NUM, where MAX_NUM is a constant that is to be set to the value 10.

SEP: 'Magic Numbers' are numbers that appear somewhere in our code, and we usually have no idea where they come from and what they mean.  Therefore, all numbers except 0, 1 and 2 should be declared as constants.

.

Try it

EvenOdd

We want to write a small console program that lists the numbers from 0 to 10, next to it the value of the (number % 2), and finally whether the number is even or odd. What we see is that the remainder operator can be used to determine if a number is even or odd.

.

.

.

Try it

Money

If we are dealing with money in our programs, should we use an int data type or a double data type?  The answer is very simple when you ask yourself: can you count money?  Everything you can count uses the int data type.

That means when we work with money we should always think in cents.  However, if we then spend them, it would be better if we did not spend 120 cents but 1.20 euros.  Here too, the remainder operator '%' is of great benefit:

int money = 120;
int euros = money / 100;
int cents = money % 100;
println("The amount is " + euros + "," + cents + " Euro.");

To make sure that our code really works, we should try different inputs.  Good test candidates are the inputs: 120, 90, 100, 102 and 002.  Our program has always returned the correct output, yes?

.

Try it

BigMoney

For amounts over a thousand euros, one more comma is added for the thousands and millions, for example: 1,001,233.45 euros.  So we want to write a function formatNumericString(int cent), which gets an amount of money in cents as parameter, and returns a string that is correctly formatted.  When we test the program, we should use the above amount.  We will find that it makes sense to write a function padWithZeros().

Also here we should try different inputs, e.g. 100123345, 100123305, and 05 might be good test candidates.

.

Try it

Time

People prefer to specify the time in hours, minutes and seconds.  Computers, on the other hand, only think in seconds, seconds that have passed since midnight.  That's why we want to write a program that calculates the current time from the seconds that have passed since midnight.  For this we again need the remainder operator. It may also make sense to write a function padWithZeros() which ensures that "06" minutes are displayed instead of "6" minutes.

For testing we should try at least the following inputs: 5, 61, 85, 3600, 3601.

.

Try it

LeapYear

We have seen above how to determine if a year is a leap year.  With this knowledge, we want to write a console program that tells us if the year someone was born in was a leap year.  For example, 1996, 2000, and 2004 should be leap years, but 1800 and 1900 should not be.

.

.

.

Try it

TruthTables*

In this project we want to deal with the boolean data type and the logical operators && (and), || (or) and ^ (exclusive or).  We want to write a program that calculates and outputs the truth tables for all three operators.  Possibly helpful is the following trick how to create a boolean datatype from an number datatype:

let in1 = 0;
let b1 = (in1 != 0);

.

Try it

InteractiveMenuProgram

Very often you need a kind of menu in a console program.  The user can choose between different menu items by entering a number.  We therefore want to write a program in which the user can choose between three possibilities: if he enters '0', the program should be terminated, if he enters '1', a message should be output, and if he enters '2', nothing should happen.  The first thing you want to do is, tell the user what the options are:

println("0: Exit / 1: Print message / 2: Do nothing");

Then comes a 'Loop and a Half', in which we ask the user for the choice:

let choice = await readInt("Your choice: ");

If the user enters the '0' we end the 'Loop and a Half':

if (choice == 0) break;

After this follows a switch or cascading if for the options '1' and '2'.

.

Try it

YearlyRate

Karel wants to buy a car, so he started saving up.  He wants to buy a Mini (Mercedes is to expensive), and he has seen a used one for 5000 euros.  He saw a cheap loan from a bank of 5% a year.  What's his annual rate if he wants the loan to be paid off in five years?

For this Karel needs a program in which he can enter the loan amount (k), the interest rate (z) and the years (n).  The program should then tell him how high his annual rate (y) is.  The formula for this can be found in the Wikipedia under compound interest formula [2]:

let q = 1.0 + z;
let qn = Math.pow(q, n);
let y = k * qn * (q - 1) / (qn - 1);

It is helpful to know that floating point numbers can be read with readDouble().

.

Try it

ChessBoard

We want to draw a checkerboard pattern using GRects.  Of course, this must be a GraphicsProgram.  It is a nice, but not quite easy application of loops and residual operator '%'.

.

.

.

.

.

.

.


Questions

  1. Name three of the standard data types of JavaScript.
     
  2. What is a magic number?
     
  3. What is the difference between a graphics program and a console program?
     
  4. In the lecture you have heard of many software engineering principles. Give three examples.
     
  5. During programming there are some typical errors that happen again and again (Common Errors). Name two of those errors.
     
  6. Write a console program that asks the user for the radius of a circle, then calculates its area (area = PI * radius * radius) and prints it to the console.
     
  7. What is the difference between 'print("hi")' and 'println("hi")'?
     
  8. What does the 'readInt()' function do?
     
  9. What are the values of the variables 'x' and 'y' after the following three lines have been executed?
    a = 6;
    x = ++­­a;
    y = x++;

     
  10. Describe in your own words what the following expression means:
       (x < 0) || (x > WIDTH)
     
  11. What is the advantage of using constants?
     
  12. Compare the two 'switch' examples below, and describe their output.
    a)  let day = 0;
        switch (day) {
        case 0:
            println("Sunday");
            break;
        case 6:
            println("Saturday");
            break;
        }


    b)  let day = 0;
        switch (day) {
        case 0:
            println("Sunday");
        case 6:
            println("Saturday");
        }


     
  13. Which values can a boolean variable take?
     
  14. What data type must the variable 'b' be in the example below?
        if ( b ) {
            println("hi");
        }

     
  15. Write the test which determines whether a number y is divisible by 400.
     
  16. Recall the remainder '%' operator?  Give two examples of what you can use it for.
     
  17. People prefer to specify times in hours, minutes and seconds.  Computers prefer to calculate in seconds. For example, the time 13:35:12 for the computer simply is 48912 seconds. Use this knowledge to convert the computer time 't' into a human readable form, i.e. hours, minutes and seconds. You can also use several intermediate steps.
     
  18. When should you use a for loop and when a while loop?
     
  19. Anything you can do with a 'for' loop can also be done with a 'while' loop and vice versa.  Rewrite the following 'for' loop as a 'while' loop.
        for (let i=0; i<5; i++) {
            println(i);
        }

     
  20. Describe the structure of the 'loop-and-a-half'.  Which problem does it solve?
     
  21. Loop and a Half: Rewrite the following Karel example using the Loop and a Half. What is the advantage of the Loop and a Half?
        function run() {
          while ( frontIsClear() ) {
            putBeeper();
          }
          putBeeper();
        }

.


References

References for the topics in this chapter can be found in practically every book on Java, especially of course in [3].

[1] Jeliot 3, Program Visualization application, University of Helsinki, cs.joensuu.fi/jeliot/description.php

[2] Seite „Sparkassenformel“. In: Wikipedia, Die freie Enzyklopädie. URL: https://de.wikipedia.org/w/index.php?title=Sparkassenformel&oldid=143971427

[3] The Art and Science of Java, von Eric Roberts, Addison-Wesley, 2008

.