In this article, we will understand how to print multiplication table in triangular form. Printing multiplication table in triangular form is achieved using a loop.
Below is a demonstration of the same −
Input
Suppose our input is −
Input : 7
Output
The desired output would be −
The result is : 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
Algorithm
Step 1 - START Step 2 - Declare 3 integer values namely my_input, I and j Step 3 - Read the required values from the user/ define the values Step 4 – Using two for-loops, iterate from 1 to my_input value and calculate the i*j value. Step 5- Display the result Step 6- Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool .
import java.util.Scanner; import java.util.*; public class MultiplicationTableTrianglePattern { public static void main(String args[]){ int my_input, i, j; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.println("Enter a number "); my_input = my_scanner.nextInt(); for (i = 1; i <= my_input; i++) { for (j = 1; j <= i; j++) { System.out.print(i * j + " "); } System.out.println(); } } }
Output
Required packages have been imported A reader object has been defined Enter a number 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
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
import java.util.*; public class MultiplicationTableTrianglePattern { public static void main(String args[]){ int my_input, i, j; System.out.println("Required packages have been imported"); my_input = 7; System.out.println("The number is defined as " +my_input ); for (i = 1; i <= my_input; i++) { for (j = 1; j <= i; j++) { System.out.print(i * j + " "); } System.out.println(); } } }
Output
Required packages have been imported The number is defined as 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