How to approach this exercise? (C)
"Have a program request the user to enter an uppercase letter. Use nested loops to produce a pyramid pattern like this:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
The pattern should extend to the character entered. For example, the preceding pattern would result from an input value of E."
So far I've been doing this for a good few hours and I'm getting the 'pyramid' to format properly开发者_如何转开发 for the letters when iterating forwards 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, I feel as though I've hit a brick wall with trying to get it to iterate backwards properly. I know it should only be a few basic loops but I'm well and truly stuck. I'm sure it's easy... I think I've just been looking at it too long. Ideas?
You are so close, you only need to take a breath and you'll see it.
When you print out your character, it has to be done after this part
while(ch2 < (ch-(rows-2)))
{
printf("%c", ch2);
ch2++;
}
or it won't fall at the end of the string. What you need is another loop that starts at the character that's one below the last character printed. It should print a character and decrement that character until it has printed the 'A' character.
Since this is homework, I'll give you a chance to write that loop before telling you the exact details.
There are ways this code could probably be rewritten to make it clearer, but basing on what you have, something like this would probably work right after your current while loop.
while (ch2 > 'A')
{
ch2--;
printf("%c", ch2);
}
I do recommend attempting to refactor your code a bit to make it clearer, though. As I suggested in a comment, start off by using character literals rather than raw integers.
You can iterate down as well as up:
while(ch2 >= 'A')
{
printf("%c", ch2);
ch2--;
}
Try this:
#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;
}
精彩评论