-1

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
NoName
  • 13
  • 3

2 Answers2

4

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("* ");
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

You only initialize k in the increment part of the for loop... Hence k is uninitialized for the first iteration. It happens to have a 0 or negative value, but its initial value is actually indeterminate: the program invokes undefined behavior.

If you compile with gcc -Wall -W -O2 or clang -Weverything -O2, the compiler will warn you about this.

You should always use standard idioms, it helps avoid such mistakes.

Here is an improved version:

#include <stdio.h>

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

    printf("Enter the number of rows: ");
    if (scanf("%d", &rows) != 1)
        return 1;

    printf("\n");

    for (i = rows; i > 0; i--) {
        for (space = 0; space < rows - i; space++) {
            printf("  ");
        }
        printf("smth");
        for (k = 0; k < 2 * i - 1; k++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189