user1612099
user1612099

Reputation: 25

Why does this program not give the expected output?

This program (in C) doesn't output what I'd expect:

int main()
{
    int i, j ;
    for ( i = 1 ; i <= 2 ; i++ )
    {
        for ( j = 1 ; j <= 2 ; j++ )
        {
            if ( i == j )
                continue ;
            printf ( "\n%d %d\n", i, j ) ;
        }
    }
}

I think it should be

1 2
1 3
2 1
2 3 

But the program outputs

1 2
2 1

Why is this?

Upvotes: 0

Views: 147

Answers (2)

Graham Borland
Graham Borland

Reputation: 60681

The values of i and j go through this sequence:

i j
---
1 1
1 2
2 1
2 2

Note that the i++ and j++ increments happen after each iteration of the loop body.

The only cases where your printf is called are where i and j are different. That means you get:

1 2
2 1

Upvotes: 1

Claudi
Claudi

Reputation: 5416

Number 3 cannot be ever reached by the loops' indices.

Upvotes: 4

Related Questions