who can explain me why it's 2 ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

who can explain me why it's 2 ?

How many times will the following loop run? for (int i = 2; i < 10; i = i*i) { System.out.println(i); }

27th Jul 2017, 10:03 PM
Cheef Bakus
Cheef Bakus - avatar
9 Answers
+ 7
2*2=4 4*4=18 done with the loop. you are multiplying I by itself and that is causing it to rise so fast.
27th Jul 2017, 10:05 PM
Jordan Chapman
Jordan Chapman - avatar
+ 7
The loop that you have given is a for loop. A for loop will continue to execute for as long as the condition is met. The condition in this loop is i < 10. So, as long as the variable 'i' has a value less than 10, the for loop will continue to execute. When the loop starts, i = 2, and because 2 is less than 10, the code within the loop executes. After the first loop, 'i' is multiplied by itself. So, 2 * 2 = 4. Now the value of 'i' is 4 but because it is less than 10, the loop will execute again for the second time. And after the second loop the value of 'i' will again be multiplied by itself; 4 * 4 = 16. After the second loop, the value of 'i' will become 16, and because 16 is higher than 10, the loop will not execute for a third time.
27th Jul 2017, 10:53 PM
Imran Din
Imran Din - avatar
+ 6
2
6th Apr 2021, 11:30 AM
Abdirahman Farah
Abdirahman Farah - avatar
+ 3
2 ans
4th Jan 2021, 10:33 AM
Priya Kumari
Priya Kumari - avatar
+ 3
2
28th Jun 2022, 10:38 PM
Opanuga Stephen
Opanuga Stephen - avatar
+ 2
2
9th Oct 2020, 3:23 AM
MARY JOY MANIQUIZ
MARY JOY MANIQUIZ - avatar
0
2
28th May 2019, 9:31 PM
Rukayya Muhammad
Rukayya Muhammad - avatar
0
2
30th Apr 2022, 5:15 AM
MAREESWARAN S
MAREESWARAN S - avatar
0
2
10th May 2022, 2:25 AM
Yogarasa Ragulan
Yogarasa Ragulan - avatar