samedi 26 juin 2021

Having problems understanding following simple algorithm

public class Test1 {
    public static void main(String[] args) {
        
        int number = 0;
        for(int i=0; i<5; i++){
            if(number != 0){
            number = i * number;
            }
            else {
             number = i;
            }
            }

        System.out.println(number);
    }
}

I'm not quite sure how this algorithm works. My thought process is:

  1. We set the number to 0 by default.
  2. In the for loop we are just saying, continue counting i till it's no longer smaller than 5.
  3. We say that if the number isn't 0, we update the number by multiplying it with i. So in our case, i is 0,1,2,3 and 4, or am I missing something?
  4. Else we are saying the number is I and "i" is what we were counting?
  5. Last we print number.

If I run this code why do I get 24 as output? I don't know how this simple algorithm works.

Aucun commentaire:

Enregistrer un commentaire