Java Loops I -Solution


Problem Overview

Original Problem: Java Loops I | Hackerrank

Difficulty: Easy

Category: Loops / Basic Control Structures

Description: This exercise introduces looping as a means to perform iterative actions. You are given an integer input and asked to print its first ten multiples.

Understanding the Problem

The problem is asking us to print a multiplication table for a given input number.

Input:

A single integer in the range of 2-20 inclusive.

Output:

Ten lines of text for each of the ten multiples. Each line should show the calculation and the product.

Initial Reasoning

The original problem reads the input in for us, which means we will need to do the following:

  • Create a loop that runs ten times, once for each multiple

  • For each iteration, print the calculation and the result

Pseudocode

// Main function:
Read the input
For each of the ten multiples
	Calculate the product
	Print the full calculation

Solution Code

// Note this is one of many possible solutions
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {
    public static void main(String[] args) throws IOException {
        // Set up BufferedReader to read input
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        
        // Parse the input into an integer
        int input = Integer.parseInt(bufferedReader.readLine().trim());
        
        // Iterate once for each of the ten multiples
        for (int multiple = 1; multiple <= 10; multiple++) {
            int result = input * multiple;
            
            // Print in the required format
            System.out.println(input + " x " + multiple + " = " + result);
        }
        
        // Close the reader to free resources
        bufferedReader.close();
    }
}

Commenting on Alterations

While we have done our best to maintain similarity to the template code provided in the original problem, the following changes have been made to follow best practices:

  • Renamed variables:

    Using more descriptive names improves the clarity of the code and makes it easier for anyone reading the code to understand what each variable represents.