Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java พิมพ์ตารางคูณแบบสามเหลี่ยม

ในบทความนี้ เราจะเรียนรู้วิธีพิมพ์ตารางคูณในรูปแบบสามเหลี่ยมในภาษา Java ทำได้โดยใช้ลูปซ้อน (nested loop)

ตัวอย่างการทำงาน

อินพุต:

Input : 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

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปรจำนวนเต็ม 3 ตัว: my_input, i, j
  3. รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. ใช้ลูป for 2 ชั้น วนจาก 1 ถึง my_input คำนวณค่า i*j
  5. แสดงผลลัพธ์
  6. จบโปรแกรม

ตัวอย่างที่ 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();
        }
    }
}

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

import java.util.*;

public class MultiplicationTableTrianglePattern {
    public static void main(String args[]) {
        int my_input = 7, i, j;
        System.out.println("Required packages have been imported");
        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();
        }
    }
}

ทั้งสองตัวอย่างจะแสดงตารางคูณแบบสามเหลี่ยมสำหรับตัวเลข 7