Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaJava Program to Print the Multiplication Table in a Triangle Form

Java Program to Print the Multiplication Table in a Triangle Form

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.

  1. In function main(), firstly the number of lines n is entered.
  2. The loop for(i=0; i<rows; i++) is used to print the column number lines.
  3. 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




// Java Program to Print the Multiplication
// Table in Triangular Form
 
import java.util.*;
 
public class MultiplicationTableTrianglePattern {
 
    // Function to print tables in triangular form
 
    public static void main(String args[])
    {
        int rows, i, j;
 
        Scanner in = new Scanner(System.in);
 
        rows = 6;
 
        // Loop to print multiplication
        // table in triangular form
 
        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

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments