Re:For loops help - comp.lang.c
by tlrobinson on Wednesday May 12, 2010 @03:55AM
(#1340456)
Mostly deobfuscated:
It's too late at night for me to try to simplify that big expression in the middle...
[ Parent
| on HN ]
The big expression in the middle is effectively unpacking a 2D point encoded in z. z % 9 is the x coordinate and z / 9 is the y coordinate:
x = z % 9;
y = z / 9;
putchar (
x + y > 3 &&
x + y < 14 &&
y < x + 6 &&
y > x - 5 ? '*' : ' ' );
if (x == 8)
putchar ( '\n' );
Wolfram Alpha plots this inequality nicely:http://www.wolframalpha.com/input/?i=x+%2B+y+%3E+3+%26%26+x+...
The program is drawing on a grid 9 wide by 10 high. The loop is going over each space in this grid. It puts a * in each cell that falls within the equations described by the four inequalities. Here's a slightly more simplified version.
int putchar ( int ) ;
int main ( void )
{
int z;
int width = 9;
int height = 10;
for (z = 0; z < width * height; z++)
{
int x = z % width;
int y = z / width;
putchar (
x + y > 3 && /* top left */
x + y < 14 && /* bottom right */
y < x + 6 && /* bottom left */
y > x - 5 /* top right */
? '*' : ' ' );
if (x == width - 1)
putchar ( '\n' );
};
putchar ( '\n' ) ;
return 0;
}
It would be clearer to separate the main loop into nested loops for x and y, but I've left it as is to show a closer resemblance to the previous version.The fun part is that you can now play with the various settings. Try increasing the height and width and scaling the equations appropriately. Replace x by 2 * x or x * x for more interesting shapes. You can bound the picture by any equations you like. Example: http://ideone.com/53Qh3