AI Hints
Home›Java Tutorial›Counting and Summing, Infinite Loops and Off-by-One, Practice: Times Table
Java · Lesson 45 of 120

Practice: Times Table

Put module five together.

⏱ 2 min read▶ Video at 56:36🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Let's put module five together. Print a times table, neatly lined up.

  • A times table
  • With a for loop
  • Neatly lined up

The seven times table

Your turn. Pause the video, and try this. Print the seven times table, from one times seven, up to ten times seven. Make the numbers line up neatly. Here is one solution. A for loop counts from one to ten. Printf with percent two d pads each number to two characters, so the columns line up.

✍️ Exercise: The seven times table

Print 1 x 7 = 7 up to 10 x 7 = 70, with the numbers lined up.

Show hint

printf("%2d x %d = %2d%n", ...)

Show solution
Main.javajava
public class Main {
    public static void main(String[] args) {
        int n = 7;
        for (int i = 1; i <= 10; i++) {
            System.out.printf("%2d x %d = %2d%n", i, n, i * n);
        }
    }
}
Output
 1 x 7 =  7
 2 x 7 = 14
 3 x 7 = 21
 4 x 7 = 28
 5 x 7 = 35
 6 x 7 = 42
 7 x 7 = 49
 8 x 7 = 56
 9 x 7 = 63
10 x 7 = 70

What module five taught

While loops repeat while a condition is true. Do while runs at least once. For loops count, with a start, condition, and step. Break leaves, and continue skips. And loops can find, count, and sum.

keyvalue
whilerepeat while true
do whileat least once
forcounting loops
break / continueleave / skip

Summary

Your programs can now repeat work. That's the end of module five. Next module, arrays.

Key takeaways
  • while, do while
  • for
  • break, continue
Next up: What an Array Is — many values in one variable