I wasn't going to post my whole code here because I thought it might be a give away but since it has already been done, I will. I hope that is OK.
Before I post it, one caveat though...
I am very new to C. I have been exposed to it for a whole 4 weeks and I've only learnt a few functions and control structures so I am sure that this is nowhere near the best way to do this. If you are learning, you might not want to take much notice of this. Perhaps some of the more experienced people here can offer a comment on what I could have done better.
Anyway, for what it's worth, here's my code. Please don't laugh...
Code:
#include <stdio.h>
int main (void) {
int rows, row_num, filled, unfilled, the_num; /* declaring the variables for use in the loops and user entry */
char the_char = '$'; /* Declaring the spacer character. As per example, it is set to a $ but could be anything*/
/* The user interface bit. Asks for the size of the grid. Works best with numbers 1-9 but will work with any
number (although the results look weird) */
printf("Enter the number of columns/rows: ");
scanf("%d", &rows);
/* Setting up the values for the variables, at this stage they are all either the same as the number
entered by the user or are zero */
the_num = rows; /* Used to store the number to print in the grid */
filled = 0; /* Used to keep track of how many numbers should appear on the line */
unfilled = rows; /* Used to keep track of how many spacer characters are on the line */
row_num = 0; /* Used to keep track of which row or line is being printed */
/* This is the outer loop. Each loop prints 1 line of $'s and Numbers */
while (row_num < rows) {
unfilled = (rows - row_num); /* This sets the number of $'s to print to 1 less on each line */
/* This is the first of 2 inner loops. This one prints the spacer character ($ in this case) */
while (unfilled > 0) {
printf ("%c", the_char);
unfilled = (unfilled - 1);
}
filled = row_num; /* This sets the number of numbers to print to 1 more on each line */
/* This is the second of the 2 inner loops. This one prints the number */
while (filled > 0) {
printf("%d", the_num);
filled = (filled - 1);
}
printf("\n"); /* This prints a new line so that, on the next outer loop, the text prints on it's own line */
row_num = (row_num + 1); /* Keeps track of how many lines there have been and ends if it reaches the number entered */
}
return 0;
}
Well, at least it works.
I have commented the hell out of it in the hopes that it will help you understand what I've done and why I've done it.
Any questions or comments? Let me know.