Java Loops I | HackerRank Solution

Java Loops I | HackerRank Solution

Java Loops I asks you to print the first ten multiples of a number, one per line, in a fixed format like 2 x 3 = 6. The loop part is short. What makes this problem useful is that it is a good place to practise two things beginners often skip: writing a clean counting loop, and building formatted output with printf instead of gluing strings together with +.

You might ask why bother with printf when string joining works. The answer is that later problems will ask for padded columns, fixed decimal places or leading zeros, and printf handles all of those with a short pattern. Learning it on an easy problem means you are not learning it under pressure in a test.

Problem

You are given an integer N. For each i from 1 to 10, print one line of the form N x i = result, where result is the product of N and i.

Input format: one integer N.

Output format: ten lines, in increasing order of i, with one space around x and around =.

Constraints: 2 ≤ N ≤ 20.

Input:
2

Output:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

Approach

  1. Read N with a Scanner.
  2. Run a loop with a counter i that takes the values 1, 2, ..., 10.
  3. On each round, print one line using a format pattern that has three slots: one for N, one for i, and one for N * i.

The pattern is the interesting part. Write the line once as a template, "%d x %d = %d%n", and let Java fill in the blanks. Each %d is a slot for a whole number, and the values after the pattern fill those slots from left to right. You can see the final shape of the line just by reading the template, which is harder to do with a chain of + signs.

Dry run with N = 2: when i = 1, the three slots get 2, 1 and 2, giving 2 x 1 = 2. When i = 7, they get 2, 7 and 14, giving 2 x 7 = 14. After i = 10 prints 2 x 10 = 20, the counter becomes 11, the condition i <= 10 fails, and the program ends.

Solution in Java

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        scanner.close();

        for (int i = 1; i <= 10; i++) {
            // %d is replaced by the next int argument, %n prints a newline
            System.out.printf("%d x %d = %d%n", N, i, N * i);
        }
    }
}

What each piece of printf means, in plain words:

  • System.out.printf(pattern, values...) prints text built from a pattern. Normal characters in the pattern are printed as they are. Special codes starting with % are replaced by the values you pass.
  • %d means "put an integer here". The d stands for decimal (base 10). If you pass a double to %d, Java throws an IllegalFormatConversionException, so the types must match.
  • %n means "end the line". Unlike println, printf does not add a newline on its own, so you have to ask for it.
  • The values are used in order. The first %d takes N, the second takes i, the third takes N * i.

The older solution here joined strings with + in a long expression like N+" "+"x"+" "+i. It produced the right output, but it is easy to lose a space in that kind of chain. It also never closed the Scanner, which does not break anything here but is a habit worth fixing.

I ran it on the sample and on the upper limit N = 20, which ends with 20 x 10 = 200, and on N = 2, the lower limit. All lines matched the expected format.

Output

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

Complexity

Ten iterations no matter what N is, so O(1) time and O(1) extra space.

Common mistakes

  • Forgetting %n (or \n) in the printf pattern. All ten results end up on one line.
  • Passing fewer values than there are %d slots. Java throws a MissingFormatArgumentException at runtime.
  • Typing a capital X or the symbol × instead of lowercase x. Output is compared character by character.
  • Off-by-one loops: i = 0 or i < 10 give eleven lines or nine lines.

Next in the Java track: Java Loops II. The same task also shows up as Day 5: Loops in 30 Days of Code.

Tip: try to solve the problem yourself before reading the solution. Use the code as a reference to check your approach, and make sure you understand why it works.

More HackerRank solutions All coding problems MCQ practice

Comments

Answered 0/0Correct 0