0
How does this code result in a six
https://code.sololearn.com/WGnnr2LNF3Dr/?ref=app import java.util.Scanner; public class Main{ public static void main(String args[]){ int x=1; for(int i =1; i< 4; i++){ x *= i; } System.out.println(x); } }
3 Answers
+ 1
First run of loop: x = 1, i = 1 x becomes x(1) * 1=1, i becomes i(1) + 1 = 2
Second run of loop: x = 1, i = 2 x becomes x(1) * 2 = 2, i becomes i(2) + 1 = 3
Third run of loop: x = 2, i = 3 x becomes x(2) * 3 = 6, i becomes i(3) + 1 = 4
Now as 4 is not less than 4, the loop stops and 6 gets printed. Use <= instead of < to include 4 in the product.
+ 1
thank you so much, nice explanation!
+ 1
you are welcome!