matthew_t_smith matthew_t_smith - 2 months ago 5x
C Question

Trouble with a C "for" Loop - Won't iterate past 1st

I am working on a problem for CS50 in which I must create a pyramid out of

's based on user input of a height. Here is what I have so far, but for height of 8, it only iterates once. For height of 7, I get about four lines of just a mess of

//Create GetPosInt() function
int GetPosInt(void) {
int n = GetInt();
while (n <= 0) {
printf("That won't work...\nRetry: ");
n = GetInt();
return n;

int main(void) {
printf("How high should Mario's pyramid be?\nHeight: ");
int h = GetPosInt();
while (h > 23) {
printf("Try something smaller!\nHeight: ");
h = GetPosInt();
char str[] = "##";
char strad[] = "#";
int l = h + 1;
for (int i = 0; i < h; i++) {
printf("%*s\n", l, str);
strcat(str, strad);
return 0;

This is my first attempt with the string.h library.

Please only tips on fixing my code - I'm certain there are other ways about it, but if it's possible this way, I'd like to keep it so for the class!


Your str array/C-String has no room to concatenate other chars than 2 chars.

As a little change you could do:

char str[128] = "";
strcat(str, "##");