[英]Reverse right angle triangle pattern with numbers and asterisks using for-loops in C++
first time posting here, I'd like help with getting the output of the code upside down while still using the for commands, below is the best I can put in a clarification.第一次在这里发帖,我希望在仍然使用 for 命令的同时将代码的 output 倒置,下面是我可以澄清的最好的。
Desired Output: Actual Output:
123456 1*****
12345* 12****
1234** 123***
123*** 1234**
12**** 12345*
1***** 123456
Code:代码:
#include <iostream>
using namespace std;
int main() {
int num, row, integ;
cout << "Please enter size: ";
cin >> integ;
for (row = 1; row <= integ; row++) {
for (num = 1; num <= row; num++) {
cout << num;
}
for (; num <= integ; num++) {
cout << "*";
}
cout << endl;
}
}
first time answering here:).第一次在这里回答:)。
change num <= row
to num <= integ - row + 1
将num <= row
更改为num <= integ - row + 1
Let's try to understand what we require.让我们试着理解我们需要什么。
We want to display number followed by stars.我们要显示数字后跟星号。 The numbers should decrease in each iteration and stars should increase.每次迭代的数字应该会减少,而星数应该会增加。
Iteration-1: display 1 to integ - 0 and 0 asterisk
Iteration-2: display 1 to integ - 1 and 1 asterisk
Iteration-3: display 1 to integ - 2 and 2 asterisk
Iteration-4: display 1 to integ - 3 and 3 asterisk
...
and so on.
As you can see, in each iteration we need to display value from 1 to (integ - x) and x asterisk, where x will starts from zero and keep on increasing.如您所见,在每次迭代中,我们需要显示从 1 到 (integ - x) 和 x 星号的值,其中 x 将从零开始并不断增加。
To put this logic in code:将此逻辑放入代码中:
int main() {
int integ;
cout << "Please enter size: ";
cin >> integ;
for(int i = 0; i < integ; ++i) {
for(int j = 0; j < integ; ++j) {
if(j < (integ-i)) {
cout << j+1;
} else {
cout << '*';
}
}
std::cout << '\n';
}
}
And here is the output:这是 output:
123456
12345*
1234**
123***
12****
1*****
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.