Search code examples
javamultiplication

Triangular Multiplication Table


I'm new to Java. I'm trying to make a triangular multiplication table that looks somewhat like this:

Enter # of rows 7

1   2   3   4   5   6   7
1
2   4
3   6   9
4   8   12  16  
5   10  15  20 25
6   12  18  24 30 36
7   14  21  28 35 42 49

Each row/column has to be numbered, and I have no idea how to do this. My code is seemingly waaay off, as I get an infinite loop that doesn't contain the correct values. Below you will find my code.

public class Prog166g
{
  public static void main(String args[])
   {
    int userInput, num = 1, c, d;
    Scanner in = new Scanner(System.in);

    System.out.print("Enter # of rows "); // user will enter number that will define output's           parameters
    userInput = in.nextInt();

    boolean quit = true;
    while(quit)
    {
        if (userInput > 9)
        {
            break;
        }
        else
        {
        for ( c = 1 ; c <= userInput ; c++ )
        { System.out.println(userInput*c);
          for (d = 1; d <= c; d++) // nested loop required to format numbers and "triangle" shape
          {
                System.out.print(EasyFormat.format(num,5,0));
          }
        }
    }
    }
   quit = false;
   }
} 

EasyFormat refers to an external file that's supposed to format the chart correctly, so ignore that. If someone could please point me in the right direction as far as fixing my existing code and adding code to number the columns and rows, that would be greatly appreciated!


Solution

  • Two nested for loops will do the trick:

    for (int i = 1; i < 8; i++) {
        System.out.printf("%d\t", i);
    }
    System.out.println();
    for (int i = 1; i < 8; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.printf("%d\t", i * j);
        }
        System.out.println();
    }
    

    OUTPUT

    1   2   3   4   5   6   7   
    1   
    2   4   
    3   6   9   
    4   8   12  16  
    5   10  15  20  25  
    6   12  18  24  30  36  
    7   14  21  28  35  42  49