Nested for sequence in plain C

Jan 26, 2017 at 4:52pm
Ok, first off I hope I am not totally off with the subject since this is written in C, because I want to start in C then pass to C++, hoping that my approach is correct...

Secondly please bare with me because my native language is NOT english, so reading text books in English is sometimes overwhelming, and so is trying to explain my question here.

This is a plain program in C just to illustrate how a nested "for" statement works.

So in line 18 initialization is skipped because the initial value of row was passed into the function. AND I DO UNDERSTAND that.

I give you the correct code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#include <stdio.h>

void draw_box (int, int); 

int main (void)
{
    draw_box (8, 35);

    return 0;

}

void draw_box( int row, int column) 
 {

    int col;
    for ( ; row>0; row--) /*The intializiation here is skipped because the initial value of "row" was passed to the funtion, ok I understand */
    {

        for (col=column; col>0; col--)
            printf("X");

        printf("\n");
    }
}


Now what I do not understand is why in the very same logic that row got the initial value, why on Zeus's butthole can't I skip the column initialization??

This is my faulty code just as an attempt to help you understand what I do not understand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

#include <stdio.h>

void draw_box (int, int); 

int main (void)
{
    draw_box (8, 35);

    return 0;

}

void draw_box( int row, int column) 
 {

    for ( ; row>0; row--) /*The intializiation here is skipped because the initial value of "row" was passed to the funtion */
    {

        for (; column>0; column--) /*why THIS would not work? */
            printf("X");

        printf("\n");
    }
}


Please try to explain it in the simplest language you can.
I do realize that newbie questions maybe somewhat annoying ... hopte this is not the case...
Last edited on Jan 26, 2017 at 4:53pm
Jan 26, 2017 at 5:05pm
What will be the value of column the second time through the outer loop in your second snippet?
Jan 26, 2017 at 5:14pm
ahh you code devil ... I think I got it ... it is 0! so I jump directly to line 23?
The local variable col refreshes the second row of X's while by skipping initialization as I did in the faulty code fails to refresh the X's ... am I talking correct?
Last edited on Jan 26, 2017 at 5:18pm
Jan 26, 2017 at 5:16pm
Exactly.
Jan 26, 2017 at 5:31pm
Thank you kind sir
Jan 26, 2017 at 5:41pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

void draw_box( int nrows, int ncols ) ;

int main()
{
    draw_box ( 8, 35 );
}

void draw_row( int ncols )
{
    for( ; ncols > 0 ; --ncols ) putchar( 'X' ) ; /*why does THIS work? */
    puts("") ;
}

void draw_box ( int nrows, int ncols )
{
    for( ; nrows > 0 ; --nrows ) draw_row(ncols) ;
}
Topic archived. No new replies allowed.