i've had a problem with this code, it skips to 3 asterisks, and my desired program follows the asterisks in order. such as 1 to 2 to 3 asterisks and so on. I want the program to only accept numbers and not special characters.
*
**
***
****
*****
****
***
**
*
Example of desired output ^
Code:
#include <iostream>
using namespace std;
int main() {
cout << "Enter a number: ";
int n;
cin >> n;
for (int i = 1; i <= n; i ) {
for (int j = 1; j <= n - i; j ) {
cout << " ";
}
for (int j = 1; j <= 2 * i - 1; j ) {
cout << "*";
}
cout << endl;
}
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= n - i; j ) {
cout << " ";
}
for (int j = 1; j <= 2 * i - 1; j ) {
cout << "*";
}
cout << endl;
}
return 0;
}
I input 5 for example, and the asterisks don't follow, it just skips to 3, for example, 1, 3, and so on.
CodePudding user response:
Let me give you some explanation how to find a solution for this problem.
Let us break a big problem into smaller ones.
If we look at the number of asterisks, so, just at the characters, not at the identation or leading spaces, then we see for the input 5:
Row Asterics Number of asterics
0 0
1 * 1
2 ** 2
3 *** 3
4 **** 4
5 ***** 5
6 **** 4
7 *** 3
8 ** 2
9 * 1
10 0
So, we need a function, that will transform the row number to the number of asterics. And, we see a pattern, that looks like a pyramid or triangle.
And this will lead us to the triangular function. Please read
And here with width 20: