What about this one? From sololearn code challenges Ingot few minutes ago. The correct answer must be 1, since x<x*x. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What about this one? From sololearn code challenges Ingot few minutes ago. The correct answer must be 1, since x<x*x.

public class Program { public static void main(String[] args) { int i; for ( i=6; i<i*i; i--); System.out.println(i); } }

6th Nov 2022, 10:12 AM
Oliver Pasaribu
Oliver Pasaribu - avatar
5 Answers
+ 3
The for loop itself is not doing anything because there is a semicolon at the end of the line. Just changing the variable. The indentation of the println is visually confusing, but it is executed only once. What happens in the loop: as long as i is smaller than its square, keep decrementing i 6 < 36 ✔️ 5 < 25 ✔️ 4 < 16 ✔️ 3 < 9 ✔️ 2 < 4 ✔️ 1 < 1 ✖️ At this point loop is stopped and the last value of i = 1 is printed.
7th Nov 2022, 4:15 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Yes. 1 < 1 false loop stops. And prints 1
6th Nov 2022, 10:40 AM
Jayakrishna 🇮🇳
+ 2
Ok. I agree with you.
8th Nov 2022, 12:43 PM
Oliver Pasaribu
Oliver Pasaribu - avatar
+ 1
What is challenge question actually? use description place for details..
6th Nov 2022, 10:30 AM
Jayakrishna 🇮🇳
+ 1
That is the challenge. The question is what is the output or the value of i after execution.
6th Nov 2022, 10:37 AM
Oliver Pasaribu
Oliver Pasaribu - avatar