Home > Mobile >  writing a for loop in c
writing a for loop in c

Time:03-29

everyone! i am trying to resolve a mario problem in cs50, and when i insert a for loop like that:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int height;
    int i = 0;
    int j = 9;

    do
    {
        height = get_int("establish the height of the pyramide: ");
    }
    while (height < 1 || height > 8);
    printf("you select the height of: %i\n", height);

    for (i < height; i  )
    {
        for (j > height; j  )
        {
            printf("#");
        }
    }
}

i get an error like that:

mario.c:17:12: error: relational comparison result unused [-Werror,-Wunused-comparison] for (i <= height; i ):

i've already tried declaring i inside the loop, but the resulting error is the same. what am i doing wrong here?

CodePudding user response:

In C the for loop is defined the following way

for ( expressionopt ; expressionopt ; expressionopt ) statement
for ( declaration expressionopt ; expressionopt ) statement

that is it has three parts. The first part either is an expression (possibly omitted) or a declaration.

So these for loops

for (i < height; i  )
for (j > height; j  )

do not satisfy the grammar. Moreover the condition in the second loop

j > height

does not make a sense.

Also try to define variables in the minimal scope where they are used.

It seems what you need is something like the following

for ( int i = 0 ; i < height; i  )
{
    for ( int j = 0; j < i   1; j  )
    {
        putchar( '#' );;
    }
    putchar( '\n' );
}

or maybe like the following

for (int i = 0; i < height; i  )
{
    printf( "%*c", height - i, '#' );
    for (int j = 1; j < i   1; j  )
    {
        putchar( '#' );;
    }
    putchar( '\n' );
}

CodePudding user response:

Even if you need to skip initialization in for loop, you need to put ;.

for (; i < height; i  ) {
  for (; j > height; j  ) {
    printf("#");
  }
}

Just changing it to that should work.

  • Related