ในบทความนี้ เราจะเรียนรู้วิธีพิมพ์ตารางคูณในภาษา Java ตารางคูณสร้างโดยการวนลูป 10 ครั้ง คูณค่า input กับตัวเลข 1 ถึง 10 ในแต่ละรอบ
ตัวอย่างการทำงาน
อินพุต:
Input : 16
เอาต์พุต:
16 * 1 = 16 16 * 2 = 32 16 * 3 = 48 16 * 4 = 64 16 * 5 = 80 16 * 6 = 96 16 * 7 = 112 16 * 8 = 128 16 * 9 = 144 16 * 10 = 160
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปรจำนวนเต็ม 2 ตัว:
my_input,i - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- วนลูป
forจาก 1 ถึง 10 คูณตัวเลข 1-10 กับ input ในแต่ละรอบ - แสดงผลลัพธ์ในแต่ละรอบ
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
int my_input, i;
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.print("Enter a number: ");
my_input = my_scanner.nextInt();
System.out.println("The multiplication table of " + my_input + " is:");
for (i = 1; i <= 10; ++i) {
System.out.printf("%d * %d = %d \n", my_input, i, my_input * i);
}
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class MultiplicationTable {
public static void main(String[] args) {
int my_input = 16, i;
System.out.println("The number is defined as " + my_input);
System.out.println("The multiplication table of " + my_input + " is:");
for (i = 1; i <= 10; ++i) {
System.out.printf("%d * %d = %d \n", my_input, i, my_input * i);
}
}
}
ทั้งสองตัวอย่างจะแสดงตารางคูณของ 16 ตั้งแต่ 1 ถึง 10