'writing a for loop in c
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?
Solution 1:[1]
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' );
}
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Gerhard |
