Originally Posted by
gratiafide
First time a question in the book had me stumped for a while, but I was able to figure it out.
Congratulations!
Now, just think of the kicks you get when you get to solve a problem you or your coworkers/friends/anyone has, by writing your own program. It's more than a little addictive
The indentation could use a bit of fixing, but that's a readability issue for us humans; the compiler will not care.
Assuming you wish to progress to writing command-line tools at some point, you might rewrite the initial part of your code to take the character from the command line instead of scanning it from input:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char user_letter;
char pyramid_letter;
char space_counter;
int i=0;
int j;
if (argc != 2) {
fprintf(stderr, "Usage: %s LETTER\n", argv[0]);
return EXIT_FAILURE;
}
if (argv[1][0] == '\0') {
fprintf(stderr, "No LETTER specified.\n");
return EXIT_FAILURE;
}
if (argv[1][1] != '\0' || !(argv[1][0] >= 'A' && argv[1][0] <= 'Z')) {
fprintf(stderr, "%s: Not a capital letter.\n", argv[1]);
return EXIT_FAILURE;
}
user_letter = argv[1][0];
space_counter = user_letter - 1;
Above, argv[0] is the name the program was run with, and argc is 1+the number of parameters, i.e. argc == the number of strings in the argv array.
If argc < 2 there is only the program name, no parameters.
If argc > 1, the first parameter is in argv[1]. It is then never a NULL pointer, but it may be an empty string (say, ./a.out ""), in which case argv[1][0] == '\0'.
In the above code, the first if statement checks that there is exactly one command-line parameter. (Program name and one parameter string means argc == 2.) Otherwise the program shows the usage and exits.
The second if statement checks if the first parameter is an empty string. I like to be careful, you see; it costs just a few lines of code, but saves a lot of trouble if you accidentally (say, in a script) supply an empty string.
The third if statement makes sure the first character is an ASCII uppercase letter A..Z, and only one-character long. Otherwise, it complains.