По сути, этот фрагмент кода, который вы здесь используете:
star = i;
space = i + input - star - 1; // or, space = input - 1 + i - star;
, совпадает с записью:
star = i;
space = input - 1;
Это потому, что i
и star
имеют одинаковое значение (молчит star = i
), и, следовательно, отрицать друг друга.
Теперь вы можете увидеть здесь константу? Да, значение input
нигде не меняется, и поэтому ваш код всегда на 1 меньше входного. (В этом случае ему всегда предшествуют пробелы 2
(=3-1
)), например:
*
**
***
^^ mark two spaces
И вы также забыли добавить конечный пробел после звездочки, и, следовательно, между их.
Следовательно, чтобы решить вашу проблему, вы можете временно сохранить значение
input
и уменьшать его на 1 на каждой итерации, чтобы оно выглядело как пирамида.
Пример:
void printer(int input)
{
int star;
int space;
// Store the original length of the space
int space_length = input;
for (int i = 1; i <= input; i++)
{
star = i;
// Get the number of spaces for the current iteration
space = space_length - 1;
for (int j = 0; j < space; j++) {
printf(" ");
}
for (int s = 0; s < star; s++) {
printf("* ");
// ^ note this space after the asterisk
}
// Decrease the length of the space every step
// So that it appears like a slope
// Note how we are using 'space_length' instead of input
// This is because if we decrement 'input', this loop
// will get affected, which is not what we want
space_length--;
printf("\n");
}
///////// bottom part of the tree /////////
// number of spaces needed = input - length of "_| |_" - 1
for (int i = 1; i <= input - (4 - 1); i++)
printf(" ");
printf("_| |_\n");
// number of spaces needed = input - length of "\\___/" - 1
for (int i = 1; i <= input - (4 - 1); i++)
printf(" ");
printf("\\___/\n");
}
, что дает результат:
*
* *
* * *
_| |_
\___/