Bài viết này nhằm mục đích in bash mẫu hình nửa kim tự tháp bằng ngôn ngữ lập trình C ++. Theo quan điểm của mẫu quy định sẽ được in, thuật toán sau đang được điều chỉnh để đạt được mục tiêu của chúng tôi là;
Thuật toán
Step-1 Set the length of the Bash (Height) Step-2 Outer loop to handle the number of rows Step-3 Inner loop to handle columns Step-4 Print the pattern with the character (@) Step-5 Set the pointer to a new line after each row (outside the inner loop) Step-6 Repeat the loop till the Bash Height
Ví dụ
Vì vậy, mã nguồn C ++ sau đây cuối cùng được tạo ra bằng cách tuân thủ thuật toán nói trên như sau;
#include <iostream>
using namespace std;
void PrintBash(int n){
// outer loop to handle number of rows
for (int i=0; i<n; i++){
// inner loop to handle number of columns
for(int j=0; j<=i; j++ ){
// printing character
cout << "@ ";
}
// ending line after each row
cout << endl;
}
}
int main(){
int Len = 6;
PrintBash(Len);
return 0;
} Đầu ra
Sau khi biên dịch đoạn mã trên, nửa kim tự tháp sẽ được in ra trông giống như sau.
@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @