0

Here is my code:

include

include

int main(void) {

 int h; //gettin some input.
 do
 {
     h = get_int();
     printf("height:\n"); //prompting for input.
 }
 while (h <= 0 || h > 23); //set pyramid constraints.

     for(int i = 0; i < h; i++)  //incrementing for i

{
     for(int j = 0; j < h-i-1; j++) //incrementing for j
    {printf("%s", " "); //aligning right.
    }

     for(int k = 0; k < i+2; k++)
    {printf("#"); //printing the hashes obvs.
    }
    printf("\n");// printing spaces obvs.
}   
return 0;//gettin out.

}

** Can i do this more efficiently? Perhaps not having the whole thing feeding through the while loop? Can all the for conditions be put into the same statement? Could this be done with less ints/is there a more efficient way to express the ratio between spaces, #s and \ns? is there a library that has functionality like 'align right', 'center' &&|| 'align left'?

**

Many thanks in advance, you all rock. -jeremy.

1

My solution is very similar to yours.

The printf("%s", " "); could be changed to printf(" ");. You could (not sure if you should) combine the two for-loops

    for(int j = 0; j < h-i-1; j++) //incrementing for j
    {
        printf("%s", " "); //aligning right.
    }

    for(int k = 0; k < i+2; k++)
    {
        printf("#"); //printing the hashes obvs.
    }

by doing an if/else in the loop body, or using the conditional (ternary) operator ? :

    for(int j = 0; j < h+1; j++) //incrementing for j
    {
        printf("%c", j < h-i-1 ? ' ' : '#');
    }

or use a more efficient function than printf, like putchar, for output:

    for(int j = 0; j < h+1; j++) //incrementing for j
    {
        putchar(j < h-i-1 ? ' ' : '#');
    }
| improve this answer | |
  • I haven't gone far enough ahead to know what putchar is yet, thank you very much for your optimizations. This is my first attempt at learning a coding language! Given the provided operators, functions etc how many solutions can there actually be? – Jeremy Francis Webb Jan 11 '17 at 14:25
  • In C, there are usually about Infinity+1 solutions, some less obvious than others – Blauelf Jan 11 '17 at 15:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .