<pre>
<?php
function append_space($n) {
static $a = '';
if(strlen($a) < $n) {
$a .= ' ';
return append_space($n);
}
$ret_val = $a;
$a = '';
return $ret_val;
}
function spruce($height) {
static $a = 1;
static $ast = "*";
//echo str_repeat(' ', $height-$a) . ( ($height == 0) ? '' : $ast ) . "\n";
echo append_space($height-$a) . ( ($height == 0 ) ? '' : $ast ) . "\n";
if($a < $height) {
$ast .= "**";
$a++;
spruce($height);
} else {
echo "\n";
}
}
spruce(9);
// *
// ***
// *****
//*******
?>
</pre>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* append_space(char n) {
static char a [64] = {0};
if(strlen(a) < n) {
strcat(a, " ");
return append_space(n);
}
char *retval = &a[0];
a[n] = '\0';
return retval;
}
void spruce(char height) {
static char ast[64] = "*";
static char i = 1;
printf("%s%s\n", (height-i <= 0) ? append_space(0) : append_space(height-i), (height != 0) ? ast : "");
if(i < height) {
strcat(ast, "**");
i++;
spruce(height);
}
}
int main() {
spruce(2);
return 0;
}
Przepisanie kodu z PHP na C, czy C++ pozostawiam Tobie.
Edit: Ulepszenie kodu pozostawiam*.