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

โปรแกรม Java สำหรับพิมพ์รูปแบบดาวสามเหลี่ยมด้านซ้าย


ในบทความนี้ เราจะทำความเข้าใจวิธีการพิมพ์รูปแบบดาวสามเหลี่ยมด้านซ้าย (Left Triangle Star Pattern) โดยใช้ลูป for 巢狀 และคำสั่งพิมพ์

ตัวอย่าง Input และ Output

Input:

Enter the number of rows : 8

Output:

The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปรจำนวนเต็ม 3 ตัวคือ i, j และ my_input
ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น
ขั้นตอนที่ 4 - ใช้ลูป for สองชั้นซ้อนกันเพื่อสร้างช่องว่างระหว่างตัวอักษร
ขั้นตอนที่ 5 - หลังจากลูปในสุดทำงานเสร็จ ให้ใช้ลูป for อีกตัวเพื่อพิมพ์ตัวอักษรที่ต้องการ
ขั้นตอนที่ 6 - พิมพ์บรรทัดใหม่เพื่อให้ได้จำนวนตัวอักษรที่ถูกต้องในบรรทัดถัดไป
ขั้นตอนที่ 7 - แสดงผลลัพธ์
ขั้นตอนที่ 8 - หยุด

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

ตัวอย่างนี้รับค่าจากผู้ใช้ผ่านคอนโซล

import java.util.Scanner;
public class RightTriangle {
    public static void main(String args[]) {
        int i, j, my_input;
        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 the number of rows : ");
        my_input = my_scanner.nextInt();
        System.out.println("The right triangle star pattern : ");
        for (i = 0; i < my_input; i++) {
            for (j = 2 * (my_input - i); j >= 0; j--) {
                System.out.print(" ");
            }
            for (j = 0; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the number of rows : 8
The right triangle star pattern :
        *
       * *
      * * *
     * * * *
    * * * * *
   * * * * * *
  * * * * * * *
 * * * * * * * *

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

public class RightTriangle {
    public static void main(String args[]) {
        int i, j, my_input;
        my_input = 8;
        System.out.println("The number of rows is defined as " + my_input);
        System.out.println("The right triangle star pattern : ");
        for (i = 0; i < my_input; i++) {
            for (j = 2 * (my_input - i); j >= 0; j--) {
                System.out.print(" ");
            }
            for (j = 0; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

The number of rows is defined as 8
The right triangle star pattern :
        *
       * *
      * * *
     * * * *
    * * * * *
   * * * * * *
  * * * * * * *
 * * * * * * * *