This week's book giveaway is in the Spring forum.
We're giving away four copies of Pro Spring MVC with WebFlux: Web Development in Spring Framework 5 and Spring Boot 2 and have Marten Deinum & Iuliana Cosmina on-line!
See this thread for details.
Win a copy of Pro Spring MVC with WebFlux: Web Development in Spring Framework 5 and Spring Boot 2 this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh

for loop vs while loop

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For loops cannot always be written as while loops?
Is this true? I realise that for loops are used when the number of iterations required is known and the while loop is used when the number of iterations are not known. Also with simple for loops I think a while loop could suffice. I am guessing that more complex for loops would not be able to be converted to a while loop. Can anybody please explain is newbie terms why the question is or is not true?
 
Sheriff
Posts: 16243
271
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Martin Gerard wrote:For loops cannot always be written as while loops


Not true.

Quote your sources because wherever you got that from, it shouldn't be trusted.
 
Martin Gerard
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry. Are you saying that for loops can always be written as while loops?
 
Marshal
Posts: 72946
330
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Martin Gerard wrote:. . . for loops can always be written as while loops?

Yes. Except if you use labelled continue, which is very unusual anyway.In this instance the for version is neater because you don't need to restrict the scope of i. That is what the {...} in lines 1 and 8 do.Here the while version is probably neater.The while version may look neater, and that is what most of the books teach, but the for version has the advantage that the surrounding {...} to restrict the scope of the Iterator are not necessary.
 
Saloon Keeper
Posts: 23697
161
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:The while version may look nea ter, and that is what most of the books teach, but the for version has the advantage that the surrounding {...} to restrict the scope of the Iterator are not necessary.



Could you translate that into English for me? I know it's early in the morning for me, but I can't make any sense of that.

The "for" statement is actually older than the "while" statement, I think. At least it was for the Fortran programming language (created in 1954). But you can consider it to be a macro instruction like this:

Which translates to

Back when Structured Programming was still a controversial subject, someone (possibly Edgser Dijtra) did a mathematical analytis of what the absolute minimum number of statement types was required to write all valid programs. As you can see here, a "while" loop is essential, a "for" loop is not. It's just a more compact notation for a very common case.
 
Campbell Ritchie
Marshal
Posts: 72946
330
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, I have vague memories of that sort of loop from a long time ago.
The advantage of a for over a while when using an Iterator is that the Iterator reference is limited to the scope of the loop. If you have to declare it before the loop, there is a risk of its staying in scope after the end of the loop, and suffering concurrent modification problems. Of course,
  • 1: Nobody would write a method long enough to suffer concurrent modifications, would they? And,
  • 2: Anybody wishing to iterate the whole of a collection in a loop would use a for‑each loop, wouldn't they? A for‑each loop would obviate concurrent modification problems.
  • But people are usually tauight to use a while. Maybe Streams have been out long enough that everybody would use a Stream nowadays.
     
    Junilu Lacar
    Sheriff
    Posts: 16243
    271
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Martin Gerard wrote:Sorry. Are you saying that for loops can always be written as while loops?


    Yes, and vice versa. In fact, the Go language only has a for-loop, no while-loop. That is, they think that any while-loop can be written as a for-loop

    https://kodify.net/go/while-loop/
     
    Junilu Lacar
    Sheriff
    Posts: 16243
    271
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tim Holloway wrote:a mathematical analytis of what the absolute minimum number of statement types was required to write all valid programs.


    I'd imagine that boiled down to the three fundamental program constructs of Sequence, Selection, and Iteration.

    As you can see here, a "while" loop is essential, a "for" loop is not. It's just a more compact notation for a very common case.


    As noted previously, the Go language appears to have gone the other way by deeming the while-loop redundant to a for-loop.
     
    Campbell Ritchie
    Marshal
    Posts: 72946
    330
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Junilu Lacar wrote:. . . Sequence, Selection, and Iteration . . .

    I thought that was originally sequence, selection, and recursion, which was the original definition of Turing completeness. Doesn't recursion pre‑date iteration? Of course, it is quite easy to show that recursion and iteration are semantically equivalent to each other. I didn't find Wikipedia that hepful; it didn't actually say that iteration was essential to Turing completeness, but it did hint that one can implement iteration with a combination of selection and GOTO.
     
    Tim Holloway
    Saloon Keeper
    Posts: 23697
    161
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    The concept of an Iterator isn't universal, nor, in fact, very old. While it is certainly very useful to Java, not all languages  have such a thing. Especially since not all languages are object-oriented.

    The analysis I mentioned was done specifically to justify Structured Programming. While it's hard to believe now, back in the 1970's, right after Djikstra pusblished his controversial "Goto Considered Harmful" letter, many people refused to admit that you could write "real" software without a goto statement. That analysis was done specifically to demonstrate that you could and could do so with a very small set of standard/universal building block types.

    Although FOR and WHILE can convert into each other, WHILE is atomic, where as FOR is a specific construct extended from the abstract WHILE. Go isn't the only language lacking a WHILE, though. Like I said, Fortran. Or, to be chronologically accurate, FORTRAN.

    For completeness, I should also note that there's DO-WHILE and WHILE-DO, but again, DO-WHILE is the accepted base case.

    I am quite happy, however, to use FOR where it's more convenient. Be glad there's both. I gave up on WHILE-DO ages ago, though. It's almost never a compelling choice over DO-WHILE.
     
    Junilu Lacar
    Sheriff
    Posts: 16243
    271
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Tim Holloway wrote:The concept of an Iterator isn't universal, nor, in fact, very old.


    Iterator vs iteration are two different things. Iteration refers to the repetition of a process. A for-loop, while-loop, repeat-until, do-while, these are all programming constructs that allow you to repetitively execute a set of instructions. What you're referring to, I believe, is the Iterator that comes with the standard Java library and similar mechanisms in other languages, like IEnumerable or IEnumerator in C#.
     
    Campbell Ritchie
    Marshal
    Posts: 72946
    330
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    The earliest source I have seen about Iterators, which is doubtless not the first ever, is as a pattern in the Gang of Four book
     
    Ranch Foreman
    Posts: 117
    4
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Just to add into the mix: What about "loop unrolling"?
    If you look at the lower level where loops gets execute physically on the cpu a loop is quite wasteful as it requires the cpu to implement at least one conditional jump instruction based on a comparison. You may also need to keep track of what's compared.
    So modern compilers often do loop unrolling: If the exact number of iterations is already known at compiletime what's a loop in the source becomes a long repetitive sequence of the same command.
    Why? Cause it's more performed to just keep feeding the same instruction into the cpu than have a costly comparisson. Also the cpu can be designed simpler.
    This can go as far as machine code gets altered in a way to modify the program counter so the same opcode is read over again and again. This saves space by not have the same instruction in the code mulriple times but only once and have it read multiple times.
    To come back to the base question: As any loop can be unrolled it can also be rolled back up into either form of loop - result in for vs while = both interchangable and one can be rewritten into the other.
     
    Ranch Foreman
    Posts: 427
    10
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Go having no while loop is pretty wild.
    Sure, everything can be expressed as a for, but sometimes it seems rather forced.

    There is a big mantra in Modern C++ about no raw for loops, they are considered, at best, a code smell.

    So in both C++ and Java (because of streams) it often feels like there are two parts to learning the language:
    1. learn how to write for loops
    2. stop writing the for loops
     
    Saloon Keeper
    Posts: 4505
    166
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Matthew Bendford wrote:Just to add into the mix: What about "loop unrolling"? (...)


    [digress]In the 90's I had a machine with an Arm3 cpu. There was the advice not to unroll a loop too much, otherwise it wouldn't fit in the cache.[/digress]
     
    Do not set lab on fire. Or this tiny ad:
    Thread Boost feature
    https://coderanch.com/t/674455/Thread-Boost-feature
    reply
      Bookmark Topic Watch Topic
    • New Topic