0

Here I'm trying to write the C code, but I've stuck in the error,

#include <stdio.h>

int main(void)
{
    int width = 0;
    while (! (width >= 1) || ! (width <= 8))
    {
        printf("Enter the width of the Pyramid: ");
        scanf("%i", &width);
    }

    printf("%i\n", width);

    for (int i=0; i<=width; i++)
    {
        int k = width - (i+1);

        for (int j=0; j<=width; j++)
        {
            if (j == k)
                printf("#");
                k++;

            else
                printf(" ");
        }
        printf("\n");
    }
}

Error message

**misleading indentation; statement is not part of the previous 'if' [-Werror,-Wmisleading-indentation]
                printf("#");
                ^
mario.c:21:13: note: previous statement is here
            if (j==k)
            ^
mario.c:25:13: error: expected expression
            else
            ^
2 errors generated.**

Here is visuals of image

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Omkar
  • 59
  • 1
  • 9
  • Oh, wow. I didn't expect a compiler to warn about it. – Eugene Sh. Jul 19 '21 at 16:17
  • @Eugene Sh. I'm if there is anything wrong in my post – Omkar Jul 19 '21 at 16:34
  • What compiler? The title suggests it is GCC — GCC has such detection, e.g., explicitly by [-Wmisleading-indentation](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmisleading-indentation) (the TAB size can be set by [-ftabstop](https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html#index-ftabstop) - the default is, unfortunately, 8). – Peter Mortensen May 27 '22 at 18:01
  • Why is this tagged with [CS50](https://en.wikipedia.org/wiki/CS50)? – Peter Mortensen May 27 '22 at 19:06

1 Answers1

5

In this piece of code:

            if (j==k)
                printf("#");
                k++;
                
            else
                printf(" ");

The indentation suggests that the line k++; is part of the body of the if statement, but it is not. Because there are no braces after the if, the body consists only of the following line, i.e. printf("#");. That also means that the else that follows has no corresponding if and is a syntax error.

You should always put braces around if blocks as well as for and while loops:

            if (j==k) {
                printf("#");
                k++;
            } else {
                printf(" ");
            }
dbush
  • 205,898
  • 23
  • 218
  • 273