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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
DiegoFuego
  • 93
  • 2
  • 4
  • 2
    Totally depends on the programming language. A real for-loop can't. – jpfollenius Oct 03 '09 at 17:47
  • 1
    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? – Pascal Cuoq Oct 03 '09 at 18:42
  • 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. – dmckee --- ex-moderator kitten Oct 03 '09 at 19:55
  • 2
    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. – dmckee --- ex-moderator kitten Oct 03 '09 at 20:24
  • @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. – Pascal Cuoq Oct 03 '09 at 21:12
  • @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. – Pascal Cuoq Oct 03 '09 at 21:16
  • @Pascal Cuoq I actually solved Project Euler Problem 10 with only for loops. That's how a prime sieve works. – György Andrasek Oct 14 '09 at 09:51

7 Answers7

15

Yes, easily.

while (cond) S;

for(;cond;) S;
Adam Wright
  • 48,938
  • 12
  • 131
  • 152
  • 2
    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. –  Oct 03 '09 at 18:19
  • 1
    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. – Adam Luchjenbroers Dec 29 '09 at 13:10
  • 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. – Evan Carroll Jul 24 '18 at 21:06
2

The while loop and the classical for loop are interchangable:

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

initializer
while (loop-test) {
    …
    counting-expression
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
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.

starblue
  • 55,348
  • 14
  • 97
  • 151
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.

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
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();
-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.

Pawan Sharma
  • 3,199
  • 1
  • 25
  • 32
  • 1
    You've not shown flexibility only terseness. The for loop is more terse. flexibility addresses if it can do more. – Evan Carroll Jul 24 '18 at 20:57
-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.

Samantha Branham
  • 7,350
  • 2
  • 32
  • 44