开发者

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

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.


Yes, easily.

while (cond) S;

for(;cond;) S;


The while loop and the classical for loop are interchangable:

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

initializer
while (loop-test) {
    …
    counting-expression
}


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.


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.


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();


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜