0
void draw_diamond(int n)
{
int mid_pos = ceil((double)n / 2);
int left_spaces = mid_pos-1;
int line_stars = 1;

putchar(10);
//printing from top through the middle of the diamond
for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
{
    //printing the left_spaces
    for(int i=1; i<=left_spaces; i++)
        putchar(32);

    //printing the line_stars
    for(int i=1; i<=line_stars; i++)
        putchar('*');
    putchar(10);
}

...

I have problem here, when I step into the for loop for the first time, nothing happens, for the second one for loop step is applied e.g.: if I pass 1 to n then:

mid_pos =1; left_spaces=0; line_stars=1;

it goes inside the loop with: left_spaces=-1; line_stars=3;

the for loop prints 3 stars where it should print just 1.

I'm confused, I'd appreciate it if any one could help.

MTVS
  • 2,046
  • 5
  • 26
  • 37

1 Answers1

5

Uh oh, watch out for the sneaky semicolon:

for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
                                                                            ^
                                                                            |

This ends your for statement. The loop will just run until line_stars is greater than n. By the end, line_stars will now equal 3 (because it is increased by 2). left_spaces will be -1.

Now the rest of your code which is enclosed by curly brackets will execute. The first for loop won't run at all, but the second one will run from 1 until line_stars and, as we know, line_stars is 3, so we get 3 stars printed out.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • 3
    Minor suggestion: `for(line_stars, left_spaces ;` - aside from taking up space on the line, this does absolutely nothing. use `for(;...` if you have nothing to initialize on the line. – Mats Petersson Dec 26 '12 at 00:34