ในบทความนี้ เราจะมาทำความเข้าใจวิธีการพิมพ์ตารางสูตรคูณในรูปสามเหลี่ยมกัน การพิมพ์ตารางสูตรคูณในรูปสามเหลี่ยมทำได้โดยใช้การวนซ้ำ
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
Input : 7
ผลผลิต
ผลลัพธ์ที่ต้องการจะเป็น −
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
อัลกอริทึม
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
ตัวอย่างที่ 1
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง คุณสามารถลองใช้ตัวอย่างนี้ในเครื่องมือกราวด์ของเรา
.
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();
}
}
} ผลลัพธ์
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
ตัวอย่างที่ 2
ในที่นี้ มีการกำหนดจำนวนเต็มก่อนหน้านี้ และเข้าถึงและแสดงค่าบนคอนโซล
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();
}
}
} ผลลัพธ์
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