This is a question from the book Introduction to Java by Y Daniel Liang:
Convert for loop statement to a while loop and do-while loop?
int sum = 0; for (int i = 0; i <= 7; i++) sum = sum + i;
I am pretty confused on how to convert it to a do-while loop. What am I supposed to do? Please see my code below.
public class Convert_forLoop_toWhileLoop {
public static void main(String[] args) {
int sum = 0;
int i = 0;
do {
sum = sum + i;
System.out.println(sum);
i++;
} while(i <= 7);
}
}
Depending on how scrupulous you wanna be, a "more" equivalent do
- while
-loop of your for
-loop example would be:
int sum1(int n) {
int sum = 0;
for (int i = 0; i <= n; i++) {
sum = sum + i;
}
return sum;
}
int sum2(int n) {
int sum = 0;
{
int i = 0;
if (i <= n) {
do {
sum = sum + i;
i++;
} while (i <= n);
}
}
return sum;
}
Note I wrapped your example in sum1
(passing sum1(7)
is equivalent to your case).
For those who really want to split hairs -- note Java doesn't necessarily compile the 2 functions above into the same bytecode (at least when I tested it, to my surprise). 2 extra bytecode instructions for sum2
(20 vs. 22). Just something interesting I noticed.
Like this:
int sum = 0;
int i = 0;
do {
sum += i;
i++;
} while (i <= 7);
System.out.println("The sum of 0 thru " +i + " is:" + sum);
Your answer doesnt support the case where i initial value is >= number of loops.
you need to first check the condition.
while (i <= 7) {
sum+=i;
// at the last statement increase i
i++
}
System.out.println(sum);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.