mardi 16 juin 2020

It is very simple to make this particular pattern with 3 loops, but how do I make it with 2 loops only? It should work for any odd given number [closed]

    *

  * * *

* * * * *

  * * *

    *

This is the pattern I want to get as an output... I made it with 3 loops, but how do I make it with only 2 loops?

Here is my code:

for (i = 1; i <= n; i++) {
    for (j = 1; j <= n - i; j++) {
        printf(" ");
    }
    if (i % 2 == 0) {
        printf("\n");
    }
    else {
        for (j = 1; j < 2 * i; j++) {
            if (j % 2 != 0)
                printf("");
            else
                printf(" ");
        }
        printf("\n");
    }
}
for (i = 1; i < n; i++) {
    for (j = 1; j <= i; j++) {
        printf(" ");
    }
    if (i % 2 != 0) {
        printf("\n");
    }
    else {
        for (j = 1; j <= 2 * (n - i) - 1; j++) {
            if (j % 2 != 0)
                printf("");
            else
                printf(" ");
        }
        printf("\n");
    }
}

Here I have two outer for loops for two parts of this pattern. First is for regular triangle, the second is for rotated triangle. How do I make in one outer loop and only one inner loop?

Aucun commentaire:

Enregistrer un commentaire