Java Program to Print the Multiplication Table in a Triangle Form
Last Updated :
17 Feb, 2023
In this form, a table is displayed row and column-wise, in such a way such that in every row, only the entries up to the same column number filled.
Example:
Input : rows = 6
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
Approach: The idea is to use nested loops. First, display the column numbers. Then, use a nested loop to fill out the entries of the row.
- In function main(), firstly the number of lines n is entered.
- The loop for(i=0; i<rows; i++) is used to print the column number lines.
- The loop for(i=0; i<rows; i++), is used to print the n rows entries. 4. The nested loop for(j = 0; j<=i; j++), is used to print the current entry.
Below is the implementation of the above approach.
Java
import java.util.*;
public class MultiplicationTableTrianglePattern {
public static void main(String args[])
{
int rows, i, j;
Scanner in = new Scanner(System.in);
rows = 6 ;
for (i = 1 ; i <= rows; i++) {
for (j = 1 ; j <= i; j++) {
System.out.print(i * j + " " );
}
System.out.println();
}
}
}
|
Output
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
Time Complexity: O(n2), where n is a number of rows.
Auxiliary Space: O(1) since using only constant variables
Share your thoughts in the comments
Please Login to comment...