NoName NoName - 1 year ago 54
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
loop for
, i.e. doesn't print any
the second iteration goes smoothly. I assume the problem is within
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);

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

Answer Source

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("* ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download