Answer the question
In order to leave comments, you need to log in
How to understand the work of while in a for loop?
class help {
public static void main (String args[]) {
int e;
int result;
for (int i=0;i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 в степени " + i + " равно " + result);
}
}
}
Answer the question
In order to leave comments, you need to log in
1. The for loop iterates over the numbers 0, 1, 2 ... 9
2. Inside the loop, at the beginning, result = 1, and e = i
3. Before each iteration of the while loop, a comparison with zero occurs
4. Inside the iteration, we multiply result by 2
5. At the end of the iteration, we subtract e.
Here, the only thing that matters to us is that the multiplication of result by 2 will be repeated i times,
the while loop can be rewritten here as follows:
class help {
public static void main (String args[]) {
for (var i=0;i < 10; i++) {
var result = 1;
for(var j = 0; j < i; j++)
result *= 2;
System.out.println("2 в степени " + i + " равно " + result);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question