Reputation: 261
Okay this is going to seem really dumb but bear with me please. A year ago I made a little program to perform various operations on images, and now I'm a bit rusty and having to do something vaguely similar. I'm looking at the old application in order to help me get started but there is one very simple thing my head doesn't want to understand the logic of just now. Basically where I loop through each pixel in an image in order to do something with that location, what exactly doesn't matter right now. Here is the basic idea:
for (int x = 0; x < inputImage.getWidth(); x++) {
for(int y = 0; y < inputImage.getHeight(); y++) {
*code in here*
}
}
Now what I don't get is this. Surely the logic of the nested for loops means that after every loop, both x AND y are incremented. So on the first pass, x = 0, y = 0. Second pass, x = 1, y = 1 and so on. This would mean that you only ever choose diagonal pixels going from the top left of the image to the bottom right, missing out a ton of pixels such as one located at x = 0, y = 1. I KNOW this is simple and surely makes sense but I'm just not getting the logic right now! Many thanks.
Upvotes: 1
Views: 701
Reputation: 45
No. Both x
and y
are not actually incremented simultaneously.
y
goes from 0
to inputImage.height-1
for every x
from 0
to inputImage.width-1
. That means, you traverse the first column completely before moving to another column on the image and so on.
Upvotes: 1
Reputation: 131600
No, that's not what nested loops do at all. The y
loop is wholly inside the body of the x
loop (that's what it means to be nested), so the entire y
loop runs at each iteration of the x
loop.
x = 0
y = 0, y = 1, y = 2, ...
x = 1
y = 0, y = 1, y = 2, ...
The behavior you're thinking of, with only iterating over diagonal elements, could be achieved like this if you wanted it:
for (int x = 0, int y = 0;
x < inputImage.getWidth && y < inputImage.getHeight;
x++, y++) {
// stuff
}
Notice how both x
and y
are incremented in the same loop; there is no nested "subloop". (Disclaimer: I haven't done Java in a while, I might have messed up the syntax a bit)
Upvotes: 1