Example of a while loop that can't be written as a for loop
Asked Answered
P

7

9

I know a while loop can do anything a for loop can, but can a for loop do anything a while loop can?

Please provide an example.

Pershing answered 3/10, 2009 at 17:39 Comment(7)
Totally depends on the programming language. A real for-loop can't.Calcareous
Assuming a language with unbounded integers and a "real for-loop", as Smasher says, and as everyone who quoted C misunderstood -- worse, I think they are serious --, consider computing the first prime larger than a given integer n. I know how to do it with while-loops. Can you do it with only for-loops?Aim
By using the phrase "real for loop" you construct a tautology. A "real for loop" is a crippled while loop, and is thus less capable, but you haven't learned anything from the exercise.Rhodos
BTW--I think I can do the next largest prime problem with for loops, but it will be very inefficient. One for loop up to n to test each number for primality and compute P the product of all primes not more than n. Then another for loop from n+1 to P+1 to test each value for primality and save the lowest value. Breaks can make it faster, but are optional.Rhodos
@dmckee I believe that using the phrase "real for loop" makes the question interesting. If the question was about writing "for(;cond;)" then so be it, my comment is off-topic then. But if, as I believe, the question is about a problem that can be solved with while-loops but not with for-loops, I think that my comment is spot on.Aim
@dmckee Well done on solving my suggested problem using only for-loops, though. We need to find a harder one. I was tempted to invoke the Ackerman function but it's defined using recursion and that confuses the issue.Aim
@Pascal Cuoq I actually solved Project Euler Problem 10 with only for loops. That's how a prime sieve works.Retentivity
T
15

Yes, easily.

while (cond) S;

for(;cond;) S;
Trieste answered 3/10, 2009 at 17:41 Comment(3)
I may as well add that this applies in C, C++, Java, C# and probably plenty of other languages that borrow heavily from C, but does not apply in e.g. Pascal.Candlestick
What I like about this answer is that it simultaneously demonstrates that it can be done, and why it's a pointless thing to do.Helpmate
I don't think this is a complete answer at all. It seems to me more a tongue cheek dismissal of the question, though strictly true.Bejarano
I
2

The while loop and the classical for loop are interchangable:

for (initializer; loop-test; counting-expression) {
    …
}

initializer
while (loop-test) {
    …
    counting-expression
}
Inversion answered 3/10, 2009 at 17:50 Comment(0)
A
1

If you have a fixed bound and step and do not allow modification of the loop variable in the loop's body, then for loops correspond to primitive recursive functions.

From a theoretical viewpoint these are weaker than general while loops, for example you can't compute the Ackermann function only with such for loops.

If you can provide an upper bound for the condition in a while loop to become true you can convert it to a for loop. This shows that in a practical sense there is no difference, as you can easily provide an astronomically high bound, say longer than the life of the universe.

Anaplastic answered 3/10, 2009 at 21:15 Comment(0)
B
1

Using C

The basic premise is of the question is that while loop can be rewritten as a for loop. Such as

init;
while (conditional) {
  statement;
  modify;
}

Being rewritten as;

for ( init; conditional; modify ) {
  statements;
}

The question is predicated on the init and modify statements being moved into the for loop, and the for loop not merely being,

init;
for (; conditional; ) {
  modify;
}

But, it's a trick question. That's untrue because of internal flow control which statements; can include. From C Programming: A Modern Approach, 2nd Edition you can see an example on Page 119,

n = 0;
sum = 0;
while ( n < 10 ) {
  scanf("%d", &i);
  if ( i == 0 )
    continue;
  sum += i;
  n++;
}

This can not be rewritten as a for loop like,

sum = 0;
for (n = 0; n < 10; n++ ) {
  scanf("%d", &i);
  if ( i == 0 )
    continue;
  sum += i;
}

Why because "when i is equal to 0, the original loop doesn't increment n but the new loop does.

And that essentially boils down to the catch,

Explicit flow control inside the while loop permits execution that a for loop (with internal init; and modify; statements) can not recreate.

Bejarano answered 24/7, 2018 at 20:53 Comment(0)
S
0

While loops can be more helpful when the number of loop iterations are not known while for loops are effective when the loop iterations are known. Consider the following code snippet for student marks, but the number of students is not known

ArrayList studentMarks = new ArrayList();

    int score = 100;
    int arraySize = 0;
    int total = 0;
    System.out.println("Enter student marks, when done press any number less than 0 0r greater than 100 to terminate entrancies\n");
    
    while(score >= 0 && score < 101) {
        System.out.print("Enter mark : ");
        
        score = scan.nextInt();
        if(score < 0 | score > 100)
            break;
        studentMarks.add(score);
        arraySize += 1;
        

        
    }
    // calculating total, average, maximum and the minimum values
    

    
    
    for(int i=0;i<studentMarks.size();i++) {
        total += studentMarks.get(i);
    System.out.println("Element at [" + (i+1)+"] : " +studentMarks.get(i)); 
        
    }
    
    System.out.println("Sum of list element is : " + total);
    System.out.println("The average of the array list : " + (total/(studentMarks.size())));
    Collections.sort(studentMarks);
    System.out.println("The minimum of the element in the list is : " + studentMarks.get(0));
    System.out.println("The maximum of the element in the list is : " + studentMarks.get(studentMarks.size()-1));
    
    scan.close();
Scurrility answered 13/6, 2021 at 21:32 Comment(0)
I
-1

In C-like languages, you can declare for loops such as this:

for(; true;)
{
    if(someCondition)
       break;
}

In languages where for is more strict, infinite loops would be a case requiring a while loop.

Imena answered 3/10, 2009 at 17:42 Comment(0)
L
-1

While loop does not have as much flexibility as a for loop has and for loops are more readable than while loops. I would demonstrate my point with an example. A for loop can have form as:

for(int i = 0, j = 0; i <= 10; i++, j++){
// Perform your operations here.
}

A while loop cannot be used like the above for loop and today most modern languages allow a for each loop as well.

In my opinion, I could be biased please forgive for that, one should not use while loop as long as it is possible to write the same code with for loop.

Legwork answered 27/9, 2012 at 12:52 Comment(1)
You've not shown flexibility only terseness. The for loop is more terse. flexibility addresses if it can do more.Bejarano

© 2022 - 2024 — McMap. All rights reserved.