I tried many things, but I fell into a swamp.
When you enter an odd number, one star in the last row pops out and you try to erase it, but it's hard...
#include<iostream>
using namespace std;
int main()
{
int num, star, line;
cout << "num ";
cin >> num;
for (line = 0; line < num/2 1; line )
{
for (star = 0; star <= line; star )
{
cout << "*";
}
for (star = num/2; star > line; star--)
{
cout << "x";
}
for (star = num/2-1; star > line; star--)
{
cout << "x";
}
for (star = 0; star <= line; star )
{
cout << "*";
}
cout << endl;
}
}
CodePudding user response:
The problem is that the last line breaks the pattern.
This is what you get:
*xxx*
**x**
******
And from your description, I assume this is what you want:
*xxx*
**x**
*****
In all the lines before the last line, the number of x
:s are odd, but in the last line, the number is even (zero). You first add three *
, then zero x
, then three *
which makes 6 characters while the previous lines only had 5.
A direct approach at fixing it could be to count the output of *
s and x
s and at the end, print num
minus the number printed so far *
s. Example:
#include <iostream>
int main() {
int num, star, line;
if(!(std::cin >> num)) return 1; // error
num |= 1; // make sure the number is odd
for (line = 0; line < num / 2 1; line ) {
int output = 0; // count how many *'s and x's you've printed
for (star = 0; star <= line; star ) {
output;
std::cout << '*';
}
for (star = num / 2; star > line; star--) {
output;
std::cout << 'x';
}
for (star = num / 2 - 1; star > line; star--) {
output;
std::cout << 'x';
}
// now print num - output asterisks:
for (star = 0; star < num - output; star ) {
std::cout << '*';
}
std::cout << '\n';
}
}