I understand the concept of one having certain advantages over the other depending on the situation but are they interchangeable in every circumstance? My textbooks writes
for (init; test; step) {
statements;
}
is identical to
init;
while (test) {
statements;
step;
}
How would I rewrite the following program in the for loop? I'm having trouble setting the value for the init and the test if i rework the following program into the for loop form.
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("this program sums the digits in an integer");
int n = readInt("enter a positive number: ");
int dsum = 0;
while ( n > 0) {
dsum += n % 10;
n /=10;
}
}
}
And yes for and while loops are interchangeable in every circumstance. A for loop is just a modified while loop that does all its declaration up front. So it declares initialization, boolean condition, and post loop incrementation. In contrast, a while loop only declares the boolean condition up front.
for() loop can always be replaced with while() loop, but sometimes, you cannot use for() loop and while() loop must be used.
Most Python for loops are easily rewritten as while loops, but not vice-versa. In other programming languages, for and while are almost interchangeable, at least in principle.
int dsum = 0;
for(int n = readInt("enter a positive number: "); n > 0; n /=10) {
dsum += n % 10;
}
As I can't stop myself from writing this, so I'll point it out.
Your for loop: -
for (init; test; step) {
statements;
}
Is not identical to the while loop you posted. The init
of the for loop will not be visible outside the loop, whereas, in your while loop, it would be. So, it's just about scope of the variable declared in init
part of for
loop. It is just inside the loop.
So, here's the exact conversion of your for loop: -
{
init;
while (test) {
statements;
step;
}
}
As far as the conversion of your specific case is concerned, I think you already got the answer.
Well, by the above explanation, the exact conversion of your while loop is a little different from the @Eric's
version above, and would be like this: -
int dsum = 0;
int n = 0;
for(n = readInt("enter a positive number: "); n > 0; n /=10) {
dsum += n % 10;
}
Note that this has a very little modification from the the @Eric's
answer, in that, it has the declaration of loop variable n
outside the for loop. This just follows from the explanation I gave.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With