Skip to content
Advertisement

I want to display multiplication table in java but only from 1 to 20

My current java program displays multiplication table from zero to infinity.

  • i want to limit that from 1 to 20 only…i want multiplication table output from 0 to 20 only.
  • i.e. i dont want multiplication table of zero or any number greater than 20 as output.
  • is it possible to do what i want using loops only
  • if not loops then how
  • i copied this problem and solution from hackerrank… Here is the code…
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
  public static void main(String[] args) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    int N = Integer.parseInt(bufferedReader.readLine().trim());
    for (int i = 0; i < 10; i) {
      System.out.println(N " x "(i 1)
        " = "(N * (i 1)));
    }
    bufferedReader.close();
  }
}```

Advertisement

Answer

most of your code is fine, you just need to add a condition to validate 1 to 20 number and also you need start your loop from 1 instead of 0, take a look at below code, this will resolve your issue

public static void main(String[] args) throws IOException {

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    int N = Integer.parseInt(bufferedReader.readLine().trim());
    if (N >= 1 && N <= 20) {
        for (int i = 1; i < 10; i++) {
            System.out.println(N + " x " + (i + 1) + " = " + (N * (i + 1)));
        }
    } else {
        System.out.println("Enter Numbers in between 1 to 20");
    }

    bufferedReader.close();

}

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement