Help with a simple C programming exercise
I'm new to C programming, having a bit of difficulty with a programming exercise, I'm sure this is simple for anyone who knows C, unfortunately you have to play by the rules of the exercise.
Here's the exercise:
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 w开发者_开发技巧ould result from an input value of E. Hint: Use an outer loop to handle the rows. Use three inner loops in a row, one to handle the spaces, one for printing letters in ascending order, and one for printing letters in descending order.
So I got this far:
#include <stdio.h>
int main(void) {
int rows;
int spaces;
char asc;
char desc;
char input;
printf("Please enter an uppercase letter: ");
scanf("%c", &input);
for (rows = 'A'; rows <= input; rows++) {
for (spaces = input; spaces > rows; spaces--) {
printf(" ");
}
for (asc = 'A'; asc <= rows; asc++) {
printf("%c", asc);
}
for (desc = asc - 2; desc >= rows; desc--) {
printf("%c", desc);
}
printf("\n");
}
return 0;
}
You're very close:
for (desc = asc - 2; desc >= 'A'; desc--) {
Note that after the second inner loop, asc
is rows + 1
. You're then initializing desc
to rows - 1
. You should be able to see why >= rows
is wrong, and will result in no iterations.
The correct condition is simply >= 'A'
.
精彩评论