Function to print a diamond shape

Jay Norwood jayn at prismnet.com
Thu Mar 20 23:23:57 PDT 2014


On Friday, 21 March 2014 at 00:31:58 UTC, bearophile wrote:
>> This is a somewhat common little exercise: Write a function
>
> Bye,
> bearophile

I like that replicate but easier for me to keep track of the 
counts if I work from the center.

int blanks[];
blanks.length = n;
int stars[];
stars.length = n;

int c = n/2; // center of diamond
int cp1 = c+1;
blanks[c]=0;
stars[c]=n;

// calculate stars and blanks in each row
for(int i=1; i<cp1; i++){
     blanks[c-i] = blanks[c+i] = i;
     stars[c-i] = stars[c+i] = n - (i*2);
}

for (int i=0; i<n; i++){
     write(" ".replicate(blanks[i]));
     writeln("*".replicate(stars[i]));
}




More information about the Digitalmars-d-learn mailing list