Is it possible to further simplify this asterisked pyramid code?

8

I'm having a simple exercise where I need to make a pyramid using a repeat structure.

The pyramid has 17 columns and 9 rows.

My program displays it correctly, Is it possible to reduce some line or some for ?

#include <stdio.h>
#include <conio.h>


main()


{
    int l,c,e;


    for (l = 1; l <= 10; l = l + 1)
    {
        for(e=1; e<=(l-1);e = e + 1)
        {
            printf(" ");
        }
        for (c = 1; c <= 10-l; c = c + 1)
        {
            printf("*");
        }

        for (c = 2; c <= 10-l; c = c + 1)
        {
            printf("*");
        }
    printf("\n");
    }
getch;
}
    
asked by anonymous 24.06.2016 / 01:22

2 answers

17

An alternative:

#include <stdio.h>
int main() {
    int l, c;
    for (l=1; l<10; l++) {
        for(c=0; c<=7+l; c++)
            printf(c<9-l?" ":"*");
        printf("\n");
    }
}

See working at IDEONE .

    
24.06.2016 / 01:39
10

Yes, it does:

#include <stdio.h>

int main() {
    for (int x = 9; x > 0; x--) {
        for(int y = 9 - x; y > 0; y--) {
            printf(" ");
        }
        for (int y = 1; y <= x * 2 - 1; y++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}

See how produces the expected result ( option if a site is out of the air ).

In addition to eliminating one of the links that only repeated what the other did, I gave an organized and modernized code. I preferred to invert the loop count and use variable name easier to read.

Do not use conio.h . It is obsolete.

But if you want to make it even simpler and use a loop, you can do this:

int main(void) {
    for (int x = 0; x < 1; x++) {
        printf("*****************\n");
        printf(" ***************\n");
        printf("  *************\n");
        printf("   ***********\n");
        printf("    *********\n");
        printf("     *******\n");
        printf("      *****\n");
        printf("       ***\n");
        printf("        *\n");
    }
    return 0;
}

When fewer deviations and variables and state changes, simpler, even if not the shortest.

If you still want the shortest one has a few possible tricks. One option:

#include <stdio.h>
int main(void) { for (int x = 9; x > 0; x--) printf("%.*s%.*s\n", 9 - x, "         ", x * 2 - 1, "*****************"); }

See working on ideone and on CodingGround .

    
24.06.2016 / 01:31