First off a little pseudo code.
for (int i=1;i<limit;i++) {
statment block
}
int i=1;
while (i<limit) {
statment block
i++;
}
In the for loop, the initialization of the variable is handled in the
structure of the loop. But if you looked at that actual code that is
produced, you would see the the for loop consists of a initialization
of the index variable, followed by a comparison and branch statement
past the end of the block, finally you would have the block, an
increment of your variable and a jump back to the comparison test at
the start of your loop.
All of this is being done explicitly with the while loop as statements
before you enter the loop, and the while loop construct. Since the
variable has to be initialized outside of the looped statements it
occurs before the while () statement. in the for() statement the
initialization is done prior to the looping of the repeated statements
by the for loop construct.
Since a while loop's construct is only for a test to stop the looping,
you have to put your increment inside the body of the loop, usually as
the last statement of the looped statements.
For loops are much clearer to read when dealing with a loop that has a
index that is incremented and tested.
While loops on the other hand are useful for non indexed as well as
indexed types of loops
Example
EOF=false;
While (~EOF) {
read one line and process
}
Here EOF is some variable that is set to false and is changed to true
when the end of the file is reached. and my statement block is to read
the file one line at a time. There is no way to know the length of the
file you are reading before hand like you can know the length of an
array, so you can't use a for loop. Thus a while loop is more general,
but you have to handle your initialization and setting of the variable
used in the loop test.
On Jun 19, 10:12 pm, "function(phil)" <[email protected]> wrote:
> Howdy again. Okay. I've looked over the process of changing a "for
> loop" to a "while loop". I've seen examples that break the variable i
> and the statement i++ out of parameters of the initial for block of
> code. I can write the code but understanding why those two areas are
> removed outside the block is not explaned. Can someone discuss with me
> why the for and while loops are different in this way. What is the
> logic and which is better to use in what situations? I refuse to go
> through this course copying code to complete the home work
> assignments, without understanding what is going on!
> Thanks
>
> Phil
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---