Chapter 1 · Foundations
Decisions and loops
Step 1 of 22 · Concept
Questions with true or false answers
In this lesson your programs decide and repeat. Both start with a question whose answer is true or
false. You met one in lesson 3: age >= 18.
| question | means | 7 ? 10 gives |
|---|---|---|
a < b | less than | true |
a > b | more than | false |
a <= b | less than or equal | true |
a >= b | more than or equal | false |
a == b | equal | false |
a != b | not equal | true |
Step 2 of 22 · Quiz
True or false?
int x = 7; Which of these is true?
Step 3 of 22 · Concept
if and else
if (temp > 25) {
System.out.println("Hot");
} else {
System.out.println("Not hot");
}
ifruns its block only when the condition istrue.elseruns its block when the condition isfalse.- Exactly one of the two blocks runs. Then the program goes on.
Step 4 of 22 · Try it
Try it: hot or not
Run the program: it prints Hot. Then change temp so that it prints Not hot.
temp > 25 must become false. Try a number that is 25 or less.
Step 5 of 22 · Concept
More than two choices: else if
For more than two choices, chain them with else if.
- Java asks the questions from the top, one by one.
- It runs the block of the first question that is
true, and skips the rest. elseat the end catches everything that is left.
Step 6 of 22 · Quiz
What will it print?
score is 72. Type exactly what this program prints.
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 70) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
Step 7 of 22 · Demo
See it run
Run it and compare with your answer. Then change score to 95, then 40, and run it each time.
Step 8 of 22 · Concept
Two questions at once: && and ||
| write | true when | example |
|---|---|---|
a && b | both are true (and) | age >= 13 && age <= 19: a teenager |
a || b | at least one is true (or) | score < 0 || score > 100: not a real score |
!a | a is false (not) | !(score >= 70): below 70 |
score < 0 || score > 100 is true for -5 and for 120, and false for 72. ! turns true into
false and back: !(72 >= 70) is false.
Step 9 of 22 · Exercise
Your turn: not a score
A score must be from 0 to 100. Add a first check: when score is below 0 or above 100, print Not a score.
With score = 120 the program must print:
Not a score
The new check goes first: the first true question wins, and 120 would get an A otherwise.
The question is score < 0 || score > 100. The old first if becomes an else if.
if (score < 0 || score > 100) {
System.out.println("Not a score");
} else if (score >= 90) {
Step 10 of 22 · Concept
A for loop counts for you
A for loop repeats its block. Its header has three parts:
| part | in the example | when |
|---|---|---|
| start | int i = 1 | once, before the first round |
| check | i <= 5 | before every round: false ends the loop |
| update | i++ (add 1 to i) | after every round |
Step 11 of 22 · Quiz
How many lines?
What does this print?
for (int i = 0; i < 3; i++) {
System.out.println("Hi " + i);
}
Step 12 of 22 · Demo
A loop and a decision
An if inside a for: every round decides again. Run it.
Step 13 of 22 · Trace
Watch the boxes change
total and i are boxes in main's frame (lesson 2). Press Next to run one round at a time.
int total = 0;
for (int i = 1; i <= 3; i++) {
total += i;
}
System.out.println("Sum: " + total);- The loop starts:
iis 1,totalis 0. Line 3 is next. total += imadetotal1.i++madei2.totalis 3,iis 3.totalis 6.ibecame 4, soi <= 3isfalse: the loop is over and its boxiis gone.- Line 5 printed
Sum: 6.
Step 14 of 22 · Exercise
Your turn: 1 to 100
Add up all the numbers from 1 to 100 with a for loop. The program must print:
Sum: 5050
Watch total grow: after i = 1 it is 1, after i = 2 it is 3, after i = 3 it is 6.
Loop with for (int i = 1; i <= 100; i++). Inside, total += i; adds i to total.
for (int i = 1; i <= 100; i++) {
total += i;
}
Step 15 of 22 · Concept
while: repeat until
while (condition) { … } repeats its block as long as the condition is true. Use it when you do not know in
advance how many rounds you need.
Step 16 of 22 · Try it
Try it: a loop that never ends
Run it. It does not stop by itself: n stays 1, so n <= 100 stays true.
Press Stop. Then add n = n * 2; inside the loop, after the print, and run it again.
Step 17 of 22 · Exercise
Your turn: the road to 1
A famous puzzle. Start from a number. Repeat:
- If it is even, halve it.
- If it is odd, make it
3 * n + 1.
The number always seems to reach 1, but nobody can say in advance how many steps it takes.
Start from n = 27 and apply the rule with a while loop until n is 1. Count the steps. The program must print:
Steps: 111
The first steps: 27 → 82 → 41 → 124 → 62 → 31 → …
The loop runs while n is not 1: while (n != 1) { … }.
Inside the loop: an if on n % 2 == 0 that halves n, an else that makes it 3 * n + 1, then steps += 1;.
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
steps += 1;
}
Step 18 of 22 · Quiz
Order matters
n is 15. What does this print?
if (n % 3 == 0) {
System.out.println("Fizz");
} else if (n % 15 == 0) {
System.out.println("FizzBuzz");
}
Step 19 of 22 · Exercise
Your turn: FizzBuzz
Print the numbers from 1 to 15, but:
FizzBuzzinstead of a number divisible by 3 and by 5,Fizzinstead of a number divisible by 3,Buzzinstead of a number divisible by 5.
The output starts 1, 2, Fizz, 4, Buzz and ends with FizzBuzz.
n % 3 == 0 is true when n is divisible by 3. Divisible by 3 and by 5 means n % 15 == 0.
Inside the loop, one chain with four branches: % 15, then % 3, then % 5, then else prints n.
if (n % 15 == 0) {
System.out.println("FizzBuzz");
} else if (n % 3 == 0) {
System.out.println("Fizz");
} else if (n % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(n);
}
Step 20 of 22 · Check yourself
Check yourself: multiples of 7
Print the first ten multiples of 7 on one line, with a space after each. Put a * right after each one that is
divisible by 3 or greater than 60.
Then print how many got a *. The output must be exactly:
7 14 21* 28 35 42* 49 56 63* 70*
Marked: 4
A for from 1 to 10 makes 7 * i. print stays on the line; System.out.println(); ends it. Count in marked.
Step 21 of 22 · Challenge · optional
Challenge: countdown
Optional. It earns the lesson's third star.
Count down from 10 to 1 on one line, then print Liftoff!:
10 9 8 7 6 5 4 3 2 1
Liftoff!
A for loop can count down. Start at 10, keep going while i >= 1.
i-- takes 1 away from i, as i++ adds 1.
Step 22 of 22 · Recap
Recap
- A comparison such as
score >= 70givestrueorfalse. if/else if/else: the firsttruequestion wins; exactly one block runs.&&needs both sidestrue;||needs at least one;!turnstrueintofalse.forhas three parts: start, check, update. Use it to count.whilerepeats as long as its question istrue. Something inside must change, or press Stop.
Next: lesson 6 puts code you use often into methods of your own.
Review
4 questions from this lesson, in a new order each time. Answer from memory: 3 of 4 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
public class Weather {
public static void main(String[] args) {
int temp = 30;
if (temp > 25) {
System.out.println("Hot");
} else {
System.out.println("Not hot");
}
}
}
public class Grade {
public static void main(String[] args) {
int score = 72;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 70) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
}
}
public class Grade {
public static void main(String[] args) {
int score = 120;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 70) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
}
}
public class Count {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even");
} else {
System.out.println(i + " is odd");
}
}
}
}
public class Sum100 {
public static void main(String[] args) {
int total = 0;
// add every number from 1 to 100 to total
System.out.println("Sum: " + total);
}
}
public class Doubling {
public static void main(String[] args) {
int n = 1;
while (n <= 100) {
System.out.print(n + " ");
// something is missing here
}
System.out.println();
System.out.println("Past 100: " + n);
}
}
public class Collatz {
public static void main(String[] args) {
int n = 27;
int steps = 0;
// while n is not 1:
// halve n if it is even, else make it 3 * n + 1
// then count the step
System.out.println("Steps: " + steps);
}
}
public class FizzBuzz {
public static void main(String[] args) {
for (int n = 1; n <= 15; n++) {
System.out.println(n);
}
}
}
public class Sevens {
public static void main(String[] args) {
// the ten multiples of 7 on one line,
// a * after each one divisible by 3 or over 60
// then the line Marked: and how many got a *
}
}
public class Countdown {
public static void main(String[] args) {
System.out.println("Liftoff!");
}
}