How to approach this exercise? (WITH)

"Ask the user to request an uppercase letter. Use nested loops to create the pyramid:

    A

   ABA

  ABCBA

 ABCDCBA

ABCDEDCBA

The pattern should apply to the entered character. For example, the previous template will be obtained from the input value E. "

So far I have been doing this for several hours, and I get a “pyramid” for correctly formatting the letters when iterating forward through the alphabet with:

#include <stdio.h>
int main(void)
{
    char ch = 0;
    char ch2 = 0;
    int rows = 0;
    printf("Enter a character: ");
    scanf("%c", &ch);
    rows = ch - 64;
    while(rows > 0)
    {
        int spaces;
        for(spaces = rows-1; spaces > 0; spaces--)
        {
            printf(" ");
        }
        ch2 = 65;
        while(ch2 < (ch-(rows-2)))
        {
            printf("%c", ch2);
            ch2++;
        }

        printf("\n");
        rows--;
    }
}

However, it seems to me that I hit a brick wall, trying to make it retreat correctly. I know that this should be just a few basic cycles, but I'm good and really stuck. I am sure it is easy ... I think I have looked at him for too long. Ideas?

+3
source share
4 answers

, , .

,

    while(ch2 < (ch-(rows-2)))
    {
        printf("%c", ch2);
        ch2++;
    }

. , , . , "A".

, , .

+1

, , , , , - , , while.

while (ch2 > 'A')
{
    ch2--;
    printf("%c", ch2);
}

, . , , .

+1

, :

while(ch2 >= 'A')
{
    printf("%c", ch2);         
    ch2--;         
} 
0

:

#include <stdio.h>

int main (int argc, const char * argv[])
{
    char ch;

    printf("Enter a character: ");
    scanf("%c", &ch);
    if(ch<'A' || ch>'Z'){
        printf("Character must be between 'A' and 'Z'\n");
        return 1;
    }

    for(int rows = ch - 'A'; rows >= 0; rows--)
    {
        char ch2;
        for(int spaces = rows; spaces > 0; spaces--)
            printf(" ");

        for(ch2='A'; ch2 < (ch-(rows-1)); ch2++) 
            printf("%c", ch2);

        for(ch2=ch2-2;ch2>='A';ch2--)
            printf("%c", ch2);

        printf("\n");
    }
    return 0;
}
0

All Articles