Reputation: 27
I'm almost there with an exercise, which I have to do for class. I'm supposed to make a single for loop creating ellipses in diagonal lines. My code shows that, however I cant figure out why the last ellipse in the top-right corner is not showing.. what am I missing?
size(400,400);
for( int x = 0; x <= 2; x++)
{
ellipse(0 + x * 200 , 0 + x * 200 , 50, 50);
ellipse(0 + x * 200, 400 + x * 200, 50, 50);
}
Upvotes: 0
Views: 3180
Reputation: 51837
It sounds a bit confusing because there are different ways to do the same thing. So far it looks like your familiar with loops which is great.
The only thing that looks like it's missing is working out the reverse of a value.
You count from 0 to 2 inclusive:
for( int x = 0; x <= 2; x++)
which gives you x with values 0,1,2
which is useful when drawing the top left to bottom right diagonal, since that matches the coordinate system (0,0 at top left).
To draw a diagonal from bottom left to top right you need different values so instead of
(0,0)
(1,1)
(2,2)
you will need:
(0,2)
(1,1)
(2,0)
One way to get the reverse value within a range is to subtract a value within the range from the maximum value of that range.
Here's a very basic sketch to illustrate the concept:
strokeWeight(10);//make points large/easy to see
int max = 2;
for(int x = 0 ; x <= max; x++){
float offset = x * 25;//spacing of 25
int reverseX = max - x;
float reverseOffset = reverseX * 25;
println("iteration " + x + " inverse iteration value: " + reverseX + " offset: " + offset + " reverseOffset: " + reverseOffset);
// point(offset,offset);
point(reverseOffset,offset);
}
Another option is to use two counters in your for loop. Hopefully your assignment doesn't consider this a cheat and it may look more confusing, but it's not too bad.
for(int x = 0, y = 3 ; x <= 3; x++, y--){
println("iteration " + x + " reverse iteration: " + y);
point(x * 25,y * 25);
}
The only parts in the for loop that changed are the first (initialization) and last (iteration) steps. You're initializing 2 variables instead of one:
In the increment step, you're handling two variables:
Upvotes: 0
Reputation: 42176
Just think about what your two ellipse()
statements are doing:
ellipse(0 + x * 200 , 0 + x * 200 , 50, 50);
: This one draws an ellipse at the upper-left corner, then an ellipse in the center, then an ellipse in the lower-right corner.
ellipse(0 + x * 200, 400 + x * 200, 50, 50);
: This one draws an ellipse in the lower-left corner. But then the other 2 ellipses it draws will be below the edge of the screen!
Remember that the Y values start at zero at the top of the window.
Try using println()
statements inside your for loop to really understand what's going on. If you still can't solve your problem, try doing this without a for loop first. Can you just call the ellipse()
function 5 times? When you have that working, then look at the coordinates you're passing in until you see a pattern that you can use inside a for loop.
Upvotes: 0