K
K
kosyan4ik12021-03-11 14:39:25
Java
kosyan4ik1, 2021-03-11 14:39:25

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


There is such a code, I understand that in the For loop we get numbers from 1 to 9, and go to the while loop,
but here I have questions, I don’t understand if we declared result = 1; , then in the loop we get result = result * 2; , that is, result = 1*2 , there is no increment on it, that is, in theory, it is result = 1; should always be the same as 2... but then how did it all work out?
Please help me figure it out..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-03-11
@kosyan4ik1

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 question

Ask a Question

731 491 924 answers to any question