NoName NoName - 3 months ago 6
C Question

C program doesn't print first line (row) but prints all the others

I'm trying to print an inverted pyramid(or triangle) with

*
, but when I run the following code it skips the
for
loop for
i=rows
, i.e. doesn't print any
*
,
the second iteration goes smoothly. I assume the problem is within
while
loop but I just don't see it clearly.

Here is the code:

#include <stdio.h>

int main() {
int k, i, space, rows;

printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("\n");

for (i = rows; i >= 1; i--, k = 0) {
for (space = 1; space <= rows - i; space++) {
printf(" ");
}
printf("smth");
while (k < 2 * i - 1) {
printf("* ");
k++;
}
printf("\n");
}
return 0;
}

Answer

The program doesn't work as you expect because you have undefined behavior in the code, since you use the uninitialized variable k before it is initialized.

Uninitialized variables have an indeterminate value, and using them (except to initialize the variable) is undefined behavior.

You should initialize k before you use it, not only at the end of the outer loop. Something like

for(i=rows,k=0; i>=1; i--,k=0)
//        ^^^^
// Added initial initialization

Or since you don't use k except in the while loop, why not turn it into a for loop? Like

for (int k = 0; k < 2 * i - 1; ++k)
    printf("* ");
Comments