Search code examples
javafor-loopnestednested-loops

Java Multiplication Table


I'm making a java program that shows the multiplication table that looks like this:

1

But I can only get the results from 1 to 5th column. How do I make the rest appear below ?

The program must only contain one for() nested loop.

This is my code so far:

import java.util.Scanner;
public class Table{
    public static void main(String[] args){

        Scanner s = new Scanner(System.in);
        System.out.print("Enter a number: ");

        int inputi = s.nextInt();

        for(int i = 1 ;i<=10;i++) {

            for(int j=1;j<=inputi && j <= 5;j++) {
                System.out.print(j + " x " + i + " = "  +(i*j) + "\t");
            }

            System.out.println();

            if(i >= 5)
            for(int j = 6; j <= inputi && j <= 10; j++){
                System.out.print(j + " x " + i + " = "  +(i*j) + "\t");
            }
        }

        System.out.println();
        System.out.println();
    }
}

Can anyone help ?

Thanks.

Edit: Sample input added.

Inputi = 7

Expected output:

Expected output

Actual output:

Actual output


Solution

  • I would suggest to

    1. Create separate variable with number of required columns
    2. Calculate how many rows will be printed (see iterations)
    3. Print rows one by one

    Please, see the code snippet below:

    int inputi = 12;
    int columns = 5;
    int iterations = inputi / columns + (inputi % columns > 0 ? 1 : 0);
    for (int iter = 0; iter < iterations; iter++) {
        for (int i = 1; i <= 10; i++) {
            for (int j = iter * columns + 1; j <= Math.min(inputi, (iter + 1) * columns); j++) {
                System.out.print(j + " x " + i + " = "  +(i * j) + "\t\t");
            }
            System.out.println();
        }
        System.out.println();
    }
    

    Note, in case inputi is huge, you may have to fill outputs with additional spaces, to avoid layout issues, when you have statements like 1 x 1 = 1 and 1 x 10000000 = 1000000