Được đưa ra với giá trị dương n và nhiệm vụ là tạo ra mẫu hình tam giác, tức là hình ảnh phản chiếu của các số được in và hiển thị kết quả
Ví dụ
Input-: n = 6 Output-:
Input-: n = 3 Output-:
Phương pháp tiếp cận được sử dụng trong chương trình dưới đây như sau -
- Nhập giá trị của n dưới dạng số nguyên dương
- Duyệt qua một vòng lặp i để biết số hàng trong một mẫu, tức là n
- Duyệt qua một vòng lặp j để biết số lượng khoảng trắng trong một mẫu
- Duyệt qua một vòng lặp khác để tìm các chữ số trong một mẫu
Thuật toán
START Step 1-> declare function to print mirror image of triangular pattern void print_mirror(int n) declare and set int temp = 1 and temp2 = 1 Loop for int i = 0 and i < n and i++ Loop For int j = n - 1 and j > i and j— print space End Loop For int k = 1 and k <= temp and k++ print abs(k - temp2) End Set temp += 2 increment temp2++ print \n Step 2-> In main() Declare int n = 6 print_mirror(n) STOP
Ví dụ
#include <bits/stdc++.h>
using namespace std;
//function to print mirror image of triangular pattern
void print_mirror(int n) {
int temp = 1, temp2 = 1;
for (int i = 0; i < n; i++) {
for (int j = n - 1; j > i; j--) {
cout << " ";
}
for (int k = 1; k <= temp; k++) {
cout << abs(k - temp2);
}
temp += 2;
temp2++;
cout << "\n";
}
}
int main() {
int n = 6;
print_mirror(n);
return 0;
} Đầu ra