Why is my C code printing out an extra line of rows?

时间:2015-06-15 15:07:44

标签: c

#include <stdio.h>

#define rows 500 //can define rows as any number

int main()
{
    int i,j;

    for(i=0;i<=rows;++i)
    {
        for(j=0;j<(2*i+1);++j)
        {
           printf("* ");
        }
        printf("\n");
    }
    return 0;
}

So here is my code, what it does is it prints the number of rows set by #define and creates a right angle triangle. But whatever I set that number to it always prints out 1 extra row of stars, and I can't figure out why.

I know I can set it as i=0;i<500;i++ and just forget about the #define statement but I'm trying to make it work with it.

3 个答案:

答案 0 :(得分:3)

You have made the condition as

i=0;i<=rows;++i

Probably a typo.It should be

i=0;i<rows;++i

as 0 to 500 means the loop runs 501 times.

答案 1 :(得分:2)

There is no issue with the #define, there is one issue with the conditional statement in the for loop.

I believe, you'er overlooking the <= operator. You need to have only < operator. Change

 for(i=0;i<=rows;++i)

to

for(i=0;i<rows;++i)

That said, the recommended signature of main() is int main(void).

答案 2 :(得分:1)

This statement:

for(i=0;i<=rows;++i)

runs for i=0,1,2,3...,rows

Therefore, it runs for a total of rows+1 times.

You can do either of below:

for(i=1;i<=rows;++i)   // for 1 to rows

or

for(i=0;i<rows;++i)     // for 0 to rows-1