Giới thiệu
Trong bài viết này, chúng ta sẽ tìm hiểu cách tạo kim tự tháp và mẫu số (pyramid and pattern). Mẫu được tạo bằng nhiều vòng lặp for lồng nhau và lệnh in.
Minh họa
Đầu vào:
The number of rows is defined as 8
Đầu ra:
The pyramid pattern :
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
6 7 8 9 10 11 10 9 8 7 6
7 8 9 10 11 12 13 12 11 10 9 8 7
8 9 10 11 12 13 14 15 14 13 12 11 10 9 8
Thuật toán
- Bắt đầu
- Khai báo 6 số nguyên:
my_input,k,i,my_count,my_temp,my_spaces - Đọc giá trị từ người dùng hoặc định nghĩa trước
- Gán 0 cho
k,my_count,my_temp - Duyệt 2 vòng lặp
forlồng nhau để tạo khoảng trắng - Sau vòng lặp trong cùng, dùng vòng
whilein giá trị(i + k - 2 * my_temp) - In dòng mới cho các dòng tiếp theo
- Hiển thị kết quả
- Kết thúc
Ví dụ 1: Nhập từ bàn phím (Scanner)
import java.util.Scanner;
public class Pyramid {
public static void main(String[] args) {
int my_input, k, i, my_count, my_temp, my_spaces;
my_input = 8;
k = 0;
my_count = 0;
my_temp = 0;
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 pyramid pattern : ");
for (i = 1; i <= my_input; ++i) {
for (my_spaces = 1; my_spaces <= my_input - i; ++my_spaces) {
System.out.print(" ");
++my_count;
}
while (k != 2 * i - 1) {
if (my_count <= my_input - 1) {
System.out.print((i + k) + " ");
++my_count;
} else {
++my_temp;
System.out.print((i + k - 2 * my_temp) + " ");
}
++k;
}
my_temp = my_count = k = 0;
System.out.println();
}
}
}
Đầu ra
Required packages have been imported
A reader object has been defined
Enter the number of rows: 8
The pyramid pattern :
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
6 7 8 9 10 11 10 9 8 7 6
7 8 9 10 11 12 13 12 11 10 9 8 7
8 9 10 11 12 13 14 15 14 13 12 11 10 9 8
Ví dụ 2: Giá trị định nghĩa trước
public class Pyramid {
public static void main(String[] args) {
int my_input, k, i, my_count, my_temp, my_spaces;
my_input = 8;
k = 0;
my_count = 0;
my_temp = 0;
System.out.println("The number of rows is defined as " + my_input);
System.out.println("The pyramid pattern : ");
for (i = 1; i <= my_input; ++i) {
for (my_spaces = 1; my_spaces <= my_input - i; ++my_spaces) {
System.out.print(" ");
++my_count;
}
while (k != 2 * i - 1) {
if (my_count <= my_input - 1) {
System.out.print((i + k) + " ");
++my_count;
} else {
++my_temp;
System.out.print((i + k - 2 * my_temp) + " ");
}
++k;
}
my_temp = my_count = k = 0;
System.out.println();
}
}
}
Đầu ra
The number of rows is defined as 8
The pyramid pattern :
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
6 7 8 9 10 11 10 9 8 7 6
7 8 9 10 11 12 13 12 11 10 9 8 7
8 9 10 11 12 13 14 15 14 13 12 11 10 9 8